Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

c - Reading from file using fgets

I am reading from file of format

1 32 43 23
32 43
123 43 54 243 
123 2222
2

Here is my code snippet.

string[100];
while(!feof(fp))
    fgets(string,100,fp)

Now, when I put every string, in the last string I am getting repetition and some more ambiguities (like something else also gets printed say 123 or so).

How to solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to check the return value of fgets. If a read has been successful, fgets returns the pointer to the buffer that you passed to it (i.e. string in your example). If the End-of-File is encountered and no characters have been read, fgets returns NULL.

Try this:

char string[100];
while(fgets(string, 100, fp)) {
    printf("%s
", string);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...