C Language File Stream String Separation Questions

Asked 2 years ago, Updated 2 years ago, 46 views

int main()

{

int i = 0;
char ch = 0;
char data[100];
FILE *fp1 = fopen("data.txt","wt");
FILE *fp2 = fopen("data.txt","rt");

fputs ("#Name: Life Coding\n", fp1);
fputs ("#resident number: 001234-3123456\n", fp1);
fputs("#phone number: 010-1111-2222\n",fp1);
fputs ("#Favorite food: salmon\n", fp1);
fputs ("#Hobby: studying computers\n", fp1);

fclose(fp1);

while(feof(fp2)==0)
{
    fgets(data,sizeof(data),fp2);
    printf("%s",data);
}

fclose(fp2);


return 0;

}

As I was learning the file stream, I learned that in files, string separation is open.

That's why I separated the strings by writing five sentences and adding a line at the end of each sentence.

However, when you execute this code, you will print the result of repeating the last sentence once again, as shown in the picture below.

If you delete the line of the last sentence, it will run normally, but I wrote the line at the end of each sentence to distinguish the string, so I wonder why the last sentence is repeated once more.

Please give me a good answer.

c

2022-09-22 18:44

1 Answers

fgets reads data up to the opening letter ('\n') or to the end of the stream.
If the last sentence ends with '\n', the eof flag is not set in the stream because it ends with just that much reading.
Then feof will return the FALSE value and the while statement will not end.
Let's continue.
Since there is no data left in the current stream, the following fgets calls will return NULL immediately after the eof flag is set.
Next is printf, right?
At this point, the previous string (=last string) still remains in the data.
(If data is read even when eof is reached, the data changes, but in this case, the data remains the same.)
When you print this out as printf, the previous string is printed once more.


2022-09-22 18:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.