How do I read data from a text file without using fscanf?

Recommended Answers

All 8 Replies

Given an opened file

while (fgets(line_buffer, sizeof line_buffer, file_handle) != NULL) {
    /* do what you want with the data stored in line_buffer */
}

How to read from a text file depends on what you want to read. If you want to read an entire line at a time then follow Aia's example, but be aware that fgets() might put the '\n' at the end of the string, if one is found in the input stream.

Another way to read the file is one character at a time, using fgetchar(). But that is probably the most difficult way to do it. I much prefer fgets() and then parse the line for individual fields such as text or numeric data.

I haven't learned much in detail at school. Can you give an example of input redirection using "<inputname"?

Thanks

Input redirection is done at the command-line level, not from within a C program. If you want to redirect a file into the C program then the C program will want to read the data from stdin. You can still use Aia's example, but replacing file_handle with stdin.

There are ways to write your c program to get the data from either stdin or a file.

int main(int argc, char* argv[])
{
   FILE* file_handle = NULL;
   if( argc > 1) // file specified on the command-line
   {
       file_handle = fopen( argv[1], "r" );
       if( file_handle == NULL) // can't open the file
       {
            printf("Error\n");
            return EXIT_FAILURE;
       }
    }
    else
       file_handle = stdin; // assume file was redirected

    // now do all the reading
}

}

commented: Very proper. +9

Another way to read the file is one character at a time, using fgetchar(). But that is probably the most difficult way to do it. I much prefer fgets() and then parse the line for individual fields such as text or numeric data.

In the standard C library there are: getc(), getchar(), fgetc(), but no fgetchar()

I normally use fread to read from a file.
But I am surprised to see none of you mentioned that method. Are there any known pitfalls in using fread ?

fread() is normally used to read binary files -- the OP asked about text files. Text files could be read with fread() but it would be somewhat more difficult than using the functions that were designed specifically for text files.

Are there any known pitfalls in using fread ?

It's comparatively awkward for reading string data.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.