Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop reading from file in C

Tags:

c

stdio

I am just trying to read each character of the file and print it out but when the file finishes reading, but I am getting a bunch of ? after it finishes reading. How do I fix it?

#include <stdio.h>

int main(void){
    FILE *fr;            /* declare the file pointer */

    fr = fopen ("some.txt", "r");  /* open the file for reading */
        /* elapsed.dta is the name of the file */
        /* "rt" means open the file for reading text */
    char c;
    while((c = getc(fr)) != NULL)
    {
        printf("%c", c);
    }
    fclose(fr);  /* close the file prior to exiting the routine */
    /*of main*/ 


    return 0;
}
like image 244
SuperString Avatar asked Jan 15 '10 03:01

SuperString


2 Answers

In spite of its name, getc returns an int, not a char, so that it can represent all of the possible char values and, in addition, EOF (end of file). If getc returned a char, there would be no way to indicate the end of file without using one of the values that could possibly be in the file.

So, to fix your code, you must first change the declaration char c; to int c; so that it can hold the EOF marker when it is returned. Then, you must also change the while loop condition to check for EOF instead of NULL.

You could also call feof(fr) to test end of file separately from reading the character. If you did that, you could leave c as a char, but you would have to call feof() after you read the character but before you printed it out, and use a break to get out of the loop.

like image 75
benzado Avatar answered Oct 28 '22 10:10

benzado


If unsuccessful, fgetc() returns EOF.

int c;
while ((c = getc(fr)) != EOF) 
{ 
    printf("%c", c); 
}
like image 23
Mitch Wheat Avatar answered Oct 28 '22 12:10

Mitch Wheat