While not terribly difficult, first timers may not know the functions to look up and use. Here is some basic code for reading a file one line at a time. The contents of the file are printed to the stdout.
Reading a File Line By Line
#include <stdio.h>
int main ( void )
{
static const char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}
/* file.txt
This text is the contents of the file named, "file.txt".
It is being used with some example code to demonstrate reading a file line by
line. More interesting things could be done with the output, but I'm trying to
keep this example very simple.
*/
/* my output
This text is the contents of the file named, "file.txt".
It is being used with some example code to demonstrate reading a file line by
line. More interesting things could be done with the output, but I'm trying to
keep this example very simple.
*/
khuman_nb 0 Newbie Poster
Dave Sinkula 2,398 long time no c Team Colleague
darylcharm 0 Newbie Poster
Tmo 0 Newbie Poster
tirmizi 0 Newbie Poster
Dionysus 0 Newbie Poster
swaythi 0 Newbie Poster
swaythi 0 Newbie Poster
bojomojo 0 Newbie Poster
kanishka.keshav 0 Newbie Poster
zoidac 0 Newbie Poster
'CoffeeLike 0 Newbie Poster
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.