Program to read file line by line in C – This is simple program that reads a text file line by line using fgets function and display the content of the file on console screen.

You can put your input text file into the current directory where you have project file or you can give the full path. Both the current path and full path has been given in the source code comments (on the top of fopen function ) that you can choose any one.

To open the file you need a FILE pointer and then use file operation functions fopen, fgets , fputs and fclose etc.

Program Example – read file line by line in C 

/* C programt to read file line by line*/
#include<stdio.h>

int main(){

	/* Create a buffer to read line may be upto 100 bytes.
	* You can change the size if you see line lenght is 
	* bigger in your text file*/
	char line [100];

	FILE *fip = NULL;// file handle initialize with NULL

	/*Open the text file in read mode as we
	* cannot modify the file accidently in the 
	* program
	*/

	//put the text file in current directory where
	//you have project file or you have to give full 
	//path e.g. fip = fopen("D:\\test\\in.txt","r+");	
	fip = fopen("in.txt","r+");

	if(fip == NULL){
		/*If file opening fails return from here itself*/
		printf("Error, Can't open file\n");
		return 0;
	}

	/*File is opened. Start reading the file line by line*/
	while ( fgets ( line, sizeof(line), fip ) != NULL )
	{
		/* Write the line on console screen*/
		fputs ( line, stdout ); 
	}

	/*close the file*/
	fclose ( fip );

	return 0;
}

Output:

You will see all the content from your text file on console screen.

Related Posts