How to Read File Line by Line Using fscanf in C
- Method 1: Reading Lines with fscanf
-
Use the
fscanf
Function to Read File Word by Word in C - Method 2: Error Handling and Best Practices
- Method 3: Using fgets for Line Reading
- Conclusion
- FAQ

Reading files is a fundamental task in programming, and in C, one of the most efficient ways to handle this is by using the fscanf
function.
This article will guide you through the process of reading a file line by line using fscanf
, ensuring you have a clear understanding of how to implement this in your C programs. Whether you are a beginner or an experienced developer, mastering file input is essential for creating robust applications. You’ll learn not just the syntax, but also best practices for handling files, including error checking and memory management. So, let’s dive in!
The fscanf
function is part of the C standard library and is primarily used for formatted input from a file. It reads data from a file stream and stores it in the specified variables. While it’s commonly used for reading formatted data, it can also be adapted for reading line by line when combined with some additional logic.
Here’s how you can do it:
Method 1: Reading Lines with fscanf
To read a file line by line using fscanf
, you’ll typically use a loop that continues until the end of the file is reached. You can use a buffer to store each line temporarily. Below is a simple example of how to achieve this.
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char buffer[256];
if (file == NULL) {
perror("Unable to open file!");
return 1;
}
while (fscanf(file, "%255[^\n]\n", buffer) != EOF) {
printf("%s\n", buffer);
}
fclose(file);
return 0;
}
Output:
First line of the file.
Second line of the file.
Third line of the file.
In this code, we open a file named example.txt
for reading. We check if the file was opened successfully; if not, we print an error message. The fscanf
function reads each line until it encounters a newline character. The format specifier %255[^\n]
tells fscanf
to read up to 255 characters or until a newline is found, ensuring we don’t overflow our buffer. After reading each line, we print it out. Finally, we close the file to free up resources.
Use the fscanf
Function to Read File Word by Word in C
Another useful case to utilize the fscanf
function is to traverse the file and parse every space-separated token. Note that the only thing to be changed from the previous example is the format specifier to "%[^\n ] "
. stat
system call is to retrieve the file size, and the value is used to pass as the malloc
argument to allocate the buffer. This method may be wasteful for some scenarios, but it ensures that even the largest single-line files can be stored in the buffer.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
const char *filename = "input.txt";
int main(int argc, char *argv[]) {
FILE *in_file = fopen(filename, "r");
if (!in_file) {
perror("fopen");
exit(EXIT_FAILURE);
}
struct stat sb;
if (stat(filename, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
char *file_contents = malloc(sb.st_size);
while (fscanf(in_file, "%[^\n ] ", file_contents) != EOF) {
printf("> %s\n", file_contents);
}
fclose(in_file);
exit(EXIT_SUCCESS);
}
Output:
> Temporary
> string
> to
> be
> written
> to
> file
It reads and prints the contents of a file named input.txt
word by word. It opens the file, uses stat to determine its size, and allocates memory accordingly. The program then uses fscanf in a loop to read each word, printing them with a >
prefix. After processing the file, it closes it and exits.
The above code demonstrates file handling, error checking, dynamic memory allocation, and string parsing in C. It’s designed to handle files of various sizes efficiently, though it may use more memory than necessary for files with significant whitespace.
Method 2: Error Handling and Best Practices
When working with files, it’s crucial to implement error handling to ensure your program can gracefully handle unexpected situations. This includes checking if the file opens successfully and whether the read operations succeed. Here’s an enhanced version of the previous example that includes error handling.
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char buffer[256];
if (file == NULL) {
perror("Unable to open file!");
return 1;
}
while (1) {
if (fscanf(file, "%255[^\n]\n", buffer) == EOF) {
break;
}
printf("%s\n", buffer);
}
fclose(file);
return 0;
}
Output:
First line of the file.
Second line of the file.
Third line of the file.
In this version, we use an infinite loop and break it when fscanf
returns EOF. This approach is a bit cleaner and allows for more straightforward error handling. If the file cannot be opened or read, the program will exit gracefully with an error message. Always remember to close the file after you are done to prevent memory leaks.
Method 3: Using fgets for Line Reading
Although fscanf
can be used to read lines, many developers prefer using fgets
, which is specifically designed for reading lines from a file. It provides better control over the input, allowing you to handle cases like buffer overflow more effectively. Here’s how you can use fgets
:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char buffer[256];
if (file == NULL) {
perror("Unable to open file!");
return 1;
}
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
Output:
First line of the file.
Second line of the file.
Third line of the file.
In this example, fgets
reads a line from the file and stores it in the buffer
. It automatically handles the newline character and ensures that we don’t read beyond the buffer size. This method is often preferred for reading lines because it simplifies the code and reduces the chance of errors.
Conclusion
Reading files line by line using fscanf
in C is a valuable skill that can enhance your programming toolkit. While fscanf
is effective, alternatives like fgets
provide additional safety and simplicity. By understanding how to implement these methods effectively, you can create robust applications that handle file input gracefully. Always remember to include error handling and clean up resources to ensure your programs run smoothly. Happy coding!
FAQ
-
What is fscanf in C?
fscanf is a function used to read formatted input from a file stream in C. -
Can I read a file without checking if it opened successfully?
It’s not recommended. Always check if the file opens successfully to avoid runtime errors. -
What happens if I exceed the buffer size in fscanf?
Exceeding the buffer size can lead to buffer overflow, causing undefined behavior or crashes. -
Is fgets better than fscanf for reading lines?
Yes, fgets is generally safer and simpler for reading lines from a file. -
How do I handle errors while reading a file in C?
Use conditional statements to check the return values of file operations and handle errors accordingly.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook