Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from file using fgets

Tags:

c

file-read

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?

like image 934
Kraken Avatar asked Feb 24 '12 16:02

Kraken


People also ask

Can fgets read from file?

(Read String from File) In the C Programming Language, the fgets function reads characters from the stream pointed to by stream. The fgets function will stop reading when n-1 characters are read, the first new-line character is encountered in s, or at the end-of-file, whichever comes first.

How does fgets () read the data from a file?

The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n -1, whichever comes first.

How do I read a line in fgets?

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

How do I use FGET?

How to use the fgets() function in C. The fgets() function in C reads up to n characters from the stream (file stream or standard input stream) to a string str . The fgets() function keeps on reading characters until: (n-1) characters have been read from the stream.


2 Answers

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\n", string);
}
like image 75
Sergey Kalinichenko Avatar answered Oct 23 '22 23:10

Sergey Kalinichenko


The eof is only reached after you have attempted to read from a file that is at the end. You have to use the return value of fgets instead (which returns NULL on eof or error and the pointer it is given otherwise):

char string[100];
while(fgets(string, 100, fp))
    // do stuff with string

Checking the return value like this will cause you never to hit the eof inside the body of the loop, like the other one, instead of in the condition.

like image 33
Seth Carnegie Avatar answered Oct 23 '22 23:10

Seth Carnegie