read a text file line by line in C

problem

You have a text file, for example a CSV file that you wish to read using the C programming language.  In this post we will see how to accomplish this.

SOLUTION

Let’s read the file line by line using the filesystem’s functions. The plan is to simply specify the filename we wish to read, open it, read it line by line (print it on the screen) and finally close it to release memory.

				
					#include <stdio.h>

#define MAX_LINE_LENGTH 100

int main(int argc, char *argv[]) {

    FILE *file;
    char line[MAX_LINE_LENGTH];
     
    file = fopen("some_text.txt", "r"); //open for reading

    if(file == NULL)
        return 1; // can't be opened
     
    while(fgets(line, MAX_LINE_LENGTH, file)){
        printf("%s", line);
    }
     
    fclose(file); //release memory

    return 0;
}
				
			

The code above declares a char array (aka string) of 100 items that will be used to read each line. We assume that each line will have less than 100 characters. The code opens the file, reads it line by line, prints every line and then closes it to avoid any memory leak.

Below we can see how it can be run.

running

Running the code above will assume we have a text file saved in the same directory with the code and the filename is some_text.txt. For this example we can assume a text file with the following contents:

				
					line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
end.

				
			
compile

For compiling the source code, the GCC is used as shown below:

				
					gcc read_file_line_by_line.c
				
			
output

To run it, using the terminal on a Mac, simply:

				
					./a.out
				
			
The output:

conclusion

In this post we saw how to simply open an existing text file and read it line by line using the legendary C programming language.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x