File operations are the program’s “means of interacting with the outside”
C is a system-oriented low-level language, yet it also provides practical file I/O functions as part of its standard library. File operations refer to the processing by which a program reads from and writes to files (text files or binary files) on a computer, and they are needed in situations such as the following.
Data persistence (saving data even after the program ends)
Logging (tracking execution details and errors)
Reading configuration from external files (enabling flexible configuration changes)
Thus, file operations are an essential technique for practical C programs.
Differences between Text Files and Binary Files
In C, there are mainly two types of files you can work with.
Text files (e.g., .txt) Files composed of human-readable character data. They are typically manipulated using functions such as fprintf and fscanf.
Binary files (e.g., .dat, .bin) Files that store machine-oriented data directly, not readable as text. They are handled with fwrite and fread.
Beginners often work with text files, but when dealing with image data, struct data, and similar, knowledge of binary files also becomes important.
Typical Flow of File Operations
When performing file operations in C, the basic flow is as follows.
Open the file: Use the fopen function to open a file and obtain a file pointer.
Read from or write to the file: Use functions such as fprintf, fscanf, fread, and fwrite to exchange data.
Close the file: Close the file and release resources with the fclose function.
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp != NULL) {
// reading operations, etc.
fclose(fp);
}
If you understand this structure, you can apply it to any file operation.
Summary: The First Step to Understanding File Operations in C
File operations in C are not just I/O; they serve as a bridge to real-world applications. By grasping file types and the basic processing flow, you’ll find it easier to understand advanced techniques you’ll learn later (such as logging, CSV handling, and using configuration files).
2. How to Open and Close Files (fopen / fclose)
File Operations Start with “fopen”
When working with files in C, the first thing you need is the fopen function. It opens a specific file and returns a “file pointer (FILE type)” for manipulating that file.
FILE *fp;
fp = fopen("example.txt", "r");
In this example, the file “example.txt” is opened in read‑only mode (r). On success, a file pointer is stored in fp; on failure, NULL is returned.
Mode Specification: Choose the Opening Method According to Use
The fopen function requires a “mode” as its second argument. This string indicates how the file will be handled, and the following types are available:
Mode
Description
“r”
Open for reading only (fails if the file does not exist)
“w”
Open for writing only (overwrites if the file exists, otherwise creates a new file)
“a”
Open for appending (creates a new file if it does not exist)
“rb”/”wb”/”ab”
Open in binary mode (commonly used on Windows)
“r+”
Open for both reading and writing (no overwriting)
“w+”
Open for both reading and writing (always overwrites)
“a+”
Open for both reading and writing (appending only allowed)
Always Check the Return Value of fopen
When opening a file, the basic step is to verify that the return value of fopen is not NULL. There are many possible reasons for failure, including the following:
The file does not exist (especially in “r” mode)
Insufficient permissions to access the file
The file path is incorrect
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("Failed to open file");
return 1;
}
Always Close with fclose When Done
After manipulating a file, you need to close the opened file using the fclose function. Failing to close a file can cause memory leaks and file corruption.
fclose(fp);
This also means “releasing resources” and is especially important when handling multiple open files.
Summary and Best Practices for fopen and fclose
Never forget to check for NULL with fopen Using perror when a file cannot be opened makes the cause easier to understand.
Follow the principle “close a file after opening it” with fclose Be sure to close files when you’re done, even before return or exit.
Practical Example: Open a Log File in Append Mode
FILE *log_fp = fopen("log.txt", "a");
if (log_fp == NULL) {
perror("Failed to open log file");
return 1;
}
fprintf(log_fp, "Program started\n");
fclose(log_fp);
Thus, opening in a mode makes appending to logs easy. Since it never overwrites and adds new entries each time, it is ideal for logging.
3. How to Write to Files (fprintf, fputs, fwrite)
File writing in C is divided into “formatted” and “binary”
C language file writing uses three functions according to the purpose.
fprintf: Text output with format specification (syntax similar to printf)
fputs: Direct text output of a string
fwrite: Used for writing structs or binary data
By understanding each characteristic and using them appropriately, you can implement data storage efficiently.
fprintf function: File output that feels like printf
ferror function: check if an I/O stream has encountered an error
if (ferror(fp)) {
fprintf(stderr, "An error occurred during file operationn");
}
feof function: check if end of file has been reached
while (!feof(fp)) {
fgets(buffer, sizeof(buffer), fp);
// ...
}
Safer approach:
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
// reading process
}
Common file operation errors and their causes
Symptom
Primary cause
Countermeasure
fopen returns NULL
File does not exist, insufficient permissions, incorrect path
Check details with perror
Writes not reflected
Unwritten due to buffering
Use fflush or fclose
Data is corrupted
Format mismatch, binary read/write errors
Verify struct sizes and order
Reading stops midway
Mistakes in newline or EOF handling
Control with fgets and return values
Summary: Robust checks are essential for safe file operations
fopen return value check (NULL test)
Explicit cause using perror or strerror
State checks with ferror and feof
Combine these to implement safe and reliable file handling.
6. Practical Example | Programs Using File Operations in C
Deepen Your Understanding Not Just with Theory, but with Real-World Usage
So far, we have covered the basics to advanced techniques of file operations in C. In this section, we will translate the knowledge you have learned into a usable form through practical sample code for file operations.
Output to Log File: Recording Application Activity
The FAQs presented here gather points that beginners to intermediate users commonly stumble on when handling files in C.
8. Summary | Master C Language File I/O to Expand Your Program’s Capabilities
Reviewing File Operations in C
In this article, we have systematically explained file operations in C, from basics to advanced topics. Specifically, we covered the following content.
File types (text/binary) and their characteristics
Opening and closing files with fopen and fclose
Writing methods using fprintf, fputs, and fwrite
Reading methods using fscanf, fgets, and fread
Basics of error handling and troubleshooting
Practical examples such as logging, CSV saving, and reading configuration files
FAQ summarizing common pitfalls for beginners
File Operations as a Bridge to the Real World
File I/O is not just an internal program process; it serves as an interface with users and other systems. Logging, loading configurations, data storage, and other practical uses rely on this essential functionality.
Next Learning Steps
If you have mastered this material, you may want to tackle the following advanced topics.
Saving arrays of structs or list structures to files
Accelerating text processing (e.g., optimizing buffer sizes)
Implementing file locking and exclusive control
Integrating with compressed files (gz, zip) using external libraries
By mastering file operations in C, your programs will evolve into practical applications. Use this article as a reference and actively implement and test the concepts.