Hello, in the next piece of code I will read the content of one file and write that to another file, accept for a certrain string which I will replace by another string that the user gave as input parameter. Now my question is; in the loop while( (ptr + lengte) + i < (zin + 18)), why do you check for zin + 18 instead of zin + 19? It does not seem correct to me, but the algoritme works, so I must see something wrong. What's wrong with thinking like this"
let's say that the fgets buffer was 5 instead of 19, and the zin buffer 6.
The string you read is: abcde. The substring you want to replace is cd. The begin address of zin is 1000. The length of the substring is 2.
while(zin + i < ptr)
#
{
#
putc(*(zin + i), output);
#
i++;
#
}
#
#
fputs(argv[4], output);
this goes correctly and you write abNEWSUBSTRING but then you come in the new while and:
#
i = 0;
#
#
while( (ptr + lengte) + i < (zin + 4))
1002 (the beginaddress of the substring) + 2 < 1000 + 4. Not true so you will not write e!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
FILE *input;
FILE *output;
char *ptr;
char zin[20];
int lengte, i = 0;
if (argc != 5)
{
printf("Aantal bestanden zijn fout\n");
exit(0);
}
if ((input = fopen(argv[1], "r")) == NULL)
{
perror("Fout ");
exit(0);
}
if ((output = fopen(argv[2], "w")) == NULL)
{
perror("Fout ");
exit(0);
}
while (fgets(zin, 19 ,input) != NULL)
{
if (strstr(zin, argv[3]) == NULL)
fputs(zin, output);
else
{
lengte = strlen(argv[3]);
ptr = strstr(zin, argv[3] );
while(zin + i < ptr)
{
putc(*(zin + i), output);
i++;
}
fputs(argv[4], output);
i = 0;
while( (ptr + lengte) + i < (zin + 18))
{
putc(*(ptr + i + lengte), output);
i++;
}
}
}
fclose(input);
fclose(output);
return 0;
}