File I/O in C is very similar to Matlab. There are two main differences. One, we have to type the FILE variable. Two, we read one value (or a single line of values) at a time, whereas by default in Matlab, you may read many values at once.
The basic steps for using a File in C are always the same:
Create a variable of type 'FILE*'.
Open the file using the 'fopen' function and assign the 'file' to the variable.
Check to make sure the file was successfully opened by checking to see if the variable NULL. If it does, an error has occured.
Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop. In the case of reading data, usually, the data is read in and placed in an array, but sometimes we process the data 'on the fly' (i.e., we do not store the data, we process it and create a result directly before reading any more data.
Example Code
Here are examples of the basic syntax for opening a file and writing to or reading from it:
- Open file in read/input mode using std::in. Check file exists or not, if it does not exist terminate the program. If file exist, run a loop until EOF (end of file) not found. Read a single character using cin in a temporary variable. And print it on the output screen.
- C program to read a range of bytes from file and print it to console. C program to append content of one text file to another.
- If the file is found, the program saves the content of the file to a string c until ' ' newline is encountered. Suppose the program.txt file contains the following text in the current directory.
Here is a comparison between reading from a file in Matlab and in C:
Matlab
Hi, I'm a newbie to programming in general and I'm really struggling with working out how on earth to do this! I am aware of how to open the stream and read the text file using fscanf, however I want to store the text in that file into a string and I'm not sure how to configure the fscanf to do this.
FGETS function: Read One Line at a Time
To read one line from a file (or the keyboard) at a time, use the fgets function.
fgets places the 'n' (newline) at the end of the line. Thus if we type in 'hello', what really goes into the variable line is [ 'h', 'e', 'l', 'l', 'o', 'n', '0' ]
fgets returns the keyword null on error. Thus we often use:
Posted on April 3, 2019 by Paul
In this article, I will show you how to read a text file line by line in C using the standard C function fgets and the POSIX getline function. At the end of the article, I will write a portable implementation of the getline function that can be used with any standard C compiler.
Reading a file line by line is a trivial problem in many programming languages, but not in C. The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.
You can find all the code examples and the input file at the GitHub repo for this article.
Let's start with a simple example of using fgets to read chunks from a text file. :
For testing the code I've used a simple dummy file, lorem.txt. This is a piece from the output of the above program on my machine:
The code prints the content of the chunk array, as filled after every call to fgets, and a marker string.
If you watch carefully, by scrolling the above text snippet to the right, you can see that the output was truncated to 127 characters per line of text. This was expected because our code can store an entire line from the original text file only if the line can fit inside our chunk array.
What if you need to have the entire line of text available for further processing and not a piece of line ? A possible solution is to copy or concatenate chunks of text in a separate line buffer until we find the end of line character.
Let's start by creating a line buffer that will store the chunks of text, initially this will have the same length as the chunk array:
Next, we are going to append the content of the chunk array to the end of the line string, until we find the end of line character. If necessary, we'll resize the line buffer:
Please note, that in the above code, every time the line buffer needs to be resized its capacity is doubled.
This is the result of running the above code on my machine. For brevity, I kept only the first lines of output:
You can see that, this time, we can print full lines of text and not fixed length chunks like in the initial approach.
Let's modify the above code in order to print the line length instead of the actual text:
This is the result of running the modified code on my machine:
In the next example, I will show you how to use the getline function available on POSIX systems like Linux, Unix and macOS. Microsoft Visual Studio doesn't have an equivalent function, so you won't be able to easily test this example on a Windows system. However, you should be able to test it if you are using Cygwin or Windows Subsystem for Linux.
Please note, how simple is to use POSIX's getline versus manually buffering chunks of line like in my previous example. Techrachaunslcsd educational technology resources. It is unfortunate that the standard C library doesn't include an equivalent function.
How To Read A Text File In C Programming
When you use getline, don't forget to free the line buffer when you don't need it anymore. Also, calling getline more than once will overwrite the line buffer, make a copy of the line content if you need to keep it for further processing.
This is the result of running the above getline example on a Linux machine:
It is interesting to note, that for this particular case the getline function on Linux resizes the line buffer to a max of 960 bytes. If you run the same code on macOS the line buffer is resized to 1024 bytes. This is due to the different ways in which getline is implemented on different Unix like systems.
As mentioned before, getline is not present in the C standard library. It could be an interesting exercise to implement a portable version of this function. The idea here is not to implement the most performant version of getline, but rather to implement a simple replacement for non POSIX systems.
We are going to take the above example and replace the POSIX's getline version with our own implementation, say my_getline. Obviously, if you are on a POSIX system, you should use the version provided by the operating system, which was tested by countless users and tuned for optimal performance.
In the next example, I will show you how to use the getline function available on POSIX systems like Linux, Unix and macOS. Microsoft Visual Studio doesn't have an equivalent function, so you won't be able to easily test this example on a Windows system. However, you should be able to test it if you are using Cygwin or Windows Subsystem for Linux.
Please note, how simple is to use POSIX's getline versus manually buffering chunks of line like in my previous example. Techrachaunslcsd educational technology resources. It is unfortunate that the standard C library doesn't include an equivalent function.
How To Read A Text File In C Programming
When you use getline, don't forget to free the line buffer when you don't need it anymore. Also, calling getline more than once will overwrite the line buffer, make a copy of the line content if you need to keep it for further processing.
This is the result of running the above getline example on a Linux machine:
It is interesting to note, that for this particular case the getline function on Linux resizes the line buffer to a max of 960 bytes. If you run the same code on macOS the line buffer is resized to 1024 bytes. This is due to the different ways in which getline is implemented on different Unix like systems.
As mentioned before, getline is not present in the C standard library. It could be an interesting exercise to implement a portable version of this function. The idea here is not to implement the most performant version of getline, but rather to implement a simple replacement for non POSIX systems.
We are going to take the above example and replace the POSIX's getline version with our own implementation, say my_getline. Obviously, if you are on a POSIX system, you should use the version provided by the operating system, which was tested by countless users and tuned for optimal performance.
The POSIX getline function has this signature:
Since ssize_t is also a POSIX defined type, usually a 64 bits signed integer, this is how we are going to declare our version:
In principle we are going to implement the function using the same approach as in one of the above examples, where I've defined a line buffer and kept copying chunks of text in the buffer until we found the end of line character:
This is how we can use the above function, for simplicity I kept the code and the function definition in the same file:
The above code gives the same results as the code that uses the POSIX's getline function:
I've also tested the code with the Microsoft C compiler and gives identical results for the same input file.
If you want to learn more about C99/C11 I would recommend reading 21st Century C: C Tips from the New School by Ben Klemens:
or the classic C Bible, The C Programming Language by B.W. Kernighan, D.M. Ritchie: