26

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?

Sicco
  • 6,167
  • 5
  • 45
  • 61
karthik
  • 351
  • 1
  • 3
  • 9

3 Answers3

34

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.

prelic
  • 4,450
  • 4
  • 36
  • 46
  • we have provided only input matrix , so obviously count is not given. In the program it is taken as i am not able to find the EOF through fscanf – karthik Aug 21 '12 at 05:08
  • 2
    while(fscanf(input,"%s",arr) != EOF) { fscanf(input,"%s",arr); len=strlen(arr); printf("%s\t",arr); } – karthik Aug 21 '12 at 05:10
  • then how it is possible to stop at EOF through fscanf ? – karthik Aug 21 '12 at 05:19
  • 3
    What do you mean? Many people in this thread have demonstrated how to stop when fscanf returns EOF. The answer below, the comment above...something like: `while(fscanf(input,"%s",arr) != EOF) {...}`. When the end of the file is reached, fscanf will return EOF, which the while loop will catch, and no more stuff will be read. In fact, you can use this to calculate your `count` variable. – prelic Aug 21 '12 at 05:23
13
while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}
perilbrain
  • 7,961
  • 2
  • 27
  • 35
4

If you have integers in your file fscanf returns 1 until integer occurs. For example:

FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
    counter = fscanf(in, "%d", &sequence);
    if ( counter == 1 ) {
        length += 1;
    }
}

To find out the end of the file with symbols you can use EOF. For example:

char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
    printf("%c", symbol); 
}
transversus
  • 181
  • 2