Below is the program to read txt file in c line by line. To understand program, you must have knowledge of Files I/O and Strings.
void perror(const char *str) :
if file "filename.txt" is empty, then it will print descriptive error message to stderr using perror() function.
char *fgets(char *str, int n, FILE *stream) :
fgets() functions reads the file line. It reads the line until the maximum length of an array or new line character encounters.
int fputs(const char *str, FILE *stream) :
The fputs() function writes line of characters into a file. It outputs string to a stream.
int fclose(FILE *fp) :
fclose() function closes the file that is being printed by the file pointer.
#include <stdio.h>
int main ( void )
{
static const char filename[] = "filename.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read the file line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
else
{
perror ( filename );
}
return 0;
}
int main ( void )
{
static const char filename[] = "filename.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read the file line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
else
{
perror ( filename );
}
return 0;
}
0 Comments