fgets() works wrong in for loop

225 views Asked by At

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?

2

There are 2 answers

2
Vlad from Moscow On BEST ANSWER

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.

0
0___________ On
int row = 6, len = 10;
char *readbuf = malloc(len * sizeof(char));
for (int i = 0; i < row; i++)
{
    printf(" %d ", i);
    if (fgets(readbuf, len, infile) == NULL)
    {
       perror("fgets");
       break;
    }
    if (fputs(readbuf, outfile) == -1)
       perror("fputs");
    if (fputs(readbuf, stdout) == -1)
       perror("fputs");
}

Your lenis too small as you have also '\n' char at the end. You need to stop the execution if you failed to read the new line.