Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find EOF through fscanf?

Tags:

I am reading matrix through file with the help of fscanf(). How can i find EOF? Even if i try to find EOF after every string caught in arr[] then also i am not able to find it.

with the help of count i am reading the input file

-12 23 3

1 2 4

int main() {     char arr[10],len;     int count=0;      FILE *input= fopen("input.txt", "r");      while(count!=7)     {               fscanf(input,"%s",arr);           //storing the value of arr in some array.                    len=strlen(arr);            count++;             if(arr[len+1]==EOF)            printf("\ni caught it\n");//here we have to exit.     } return 0; } 

Instead of count i want to exit through the loop with the EOF . how can it be solved?

like image 584
karthik Avatar asked Aug 21 '12 04:08

karthik


People also ask

Does fscanf read EOF?

fscanf returns EOF if end of file (or an input error) occurs before any values are stored. If values are stored, it returns the number of items stored; that is, the number of times a value is assigned with one of the fscanf argument pointers. EOF is returned if an error occurs before any items are matched.

What does fscanf return on EOF in C?

The fscanf() function returns the number of fields that it successfully converted and assigned. The return value does not include fields that the fscanf() function read but did not assign. The return value is EOF if an input failure occurs before any conversion, or the number of input items assigned if successful.

How do you read scanf until EOF in C?

scanf returns a count when it is forced to stop such as end of a file; For stdin which might be considered unlimited, you might use _kbhit() to sense if characters are available. CTRL-Z or something can be typed which can act as EOF on some platforms.

Does fscanf read whole files?

Description. A = fscanf( fileID , formatSpec ) reads data from an open text file into column vector A and interprets values in the file according to the format specified by formatSpec . The fscanf function reapplies the format throughout the entire file and positions the file pointer at the end-of-file marker.


2 Answers

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

like image 120
prelic Avatar answered Oct 25 '22 16:10

prelic


while (fscanf(input,"%s",arr) != EOF && count!=7) {   len=strlen(arr);    count++;  } 
like image 22
perilbrain Avatar answered Oct 25 '22 16:10

perilbrain