I am trying to use fgets
and fputs
to copy-paste a file. I wrote in two ways, one in for loop, the other in while loop. While loop works perfectly, but for loop acts weird.
I tried to debug and wrote this:
FILE *infile = fopen("infile", "r");
FILE *outfile = fopen("forLoop_outfile", "w");
int row = 6, len = 6;
char *readbuf = malloc(len * sizeof(char));
for (int i = 0; i < row; i++)
{
printf(" %d ", i);
if (fgets(readbuf, len, infile) == NULL)
perror("fgets");
if (fputs(readbuf, outfile) == -1)
perror("fputs");
if (fputs(readbuf, stdout) == -1)
perror("fputs");
}
input file:
abcde
fghij
klmno
pqrst
uvwxy
z
stdout and output file are the same:
0 abcde 1
2 fghij 3
4 klmno 5
as you can see, only the first 3 lines are read, and something when wrong for every 2 iteration. And debugging seems useless.
What's going wrong?
Actually the input file contains
abcde\n
fghij\n
klmno\n
pqrst\n
uvwxy\n
z\n
As the length of the dynamically allocated array is equal to 6
then the first call of fgets
reads only 5
characters "abcde"
and appends them with the terminating zero character '\0'
. The new line character '\n'
is not read yet. So the next call of fgets
reads this new line character '\n'
.
To resolve the problem enlarge the size of the dynamically allocated array.