0
votes

Let fp1 point to a file called file1, fp2 point to a file called file2. file1 and file2 are exactly same. And no file open errors.

But function test_fgets prints out different strings. The line printf("%s", lptr1) prints out NULL, but printf("%s", lptr2) prints out the last line of file2.

Since file1 and file2 are exactly the same, why print different outputs?

Besides, when I tried to change printf("%s", lptr1) to printf("%s\n", lptr1), it gave me a segmentation fault(core dump) error. Why is it? How does a newline character affect here?

...
#define MAXLINE 100
char line1[MAXLINE];
char line2[MAXLINE];

...
void test_fgets(FILE *fp1, FILE *fp2){

   char *lptr1;
   char *lptr2;

   while( (lptr1 = fgets(line1, MAXLINE, fp1)) && (lptr2 = fgets(line2, MAXLINE, fp2)))
          ;

   printf("%s", lptr1);
   printf("%s", lptr2); 
}
2

2 Answers

2
votes

The loop runs until fgets fails, indicated by a nullptr. Oh, the second fgets is not executed since it's a && condition, so lptr2 still holds its last line.

1
votes

In this statement

while( (lptr1 = fgets(line1, MAXLINE, fp1)) && (lptr2 = fgets(line2, MAXLINE, fp2)));

if the first expression

(lptr1 = fgets(line1, MAXLINE, fp1))

is equal to false then the second expression

(lptr2 = fgets(line2, MAXLINE, fp2))

is not evaluated. So the second printf prints the previous content of line2 because lptr2 was not changed. It is only lptr1 that was changed to NULL.

To get the desired result you should change the while loop to a do..while loop. For example

   do
   {
      lptr1 = fgets(line1, MAXLINE, fp1);
      lptr2 = fgets(line2, MAXLINE, fp2)'
   } while( lptr1 && lptr2 );