C File Read/Write Program
In C, file handling is performed using functions provided by the standard library, allowing you to read from and write to files. This capability is crucial for data persistence, enabling your programs to store and retrieve information even after they terminate.
Program: File Read/Write in C
Here's a simple program that demonstrates how to write data to a file and then read it back.
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is required for standard input/output functions likeprintf
,fgets
, and file handling functions.#include <stdlib.h>
: This header file is included for theEXIT_FAILURE
andEXIT_SUCCESS
macros.
File Pointer:
FILE *file;
: This declares a pointer to aFILE
type, which is used to handle the file.
Writing to a File:
- Open File:
This opens (or creates) a file named
example.txt
in write mode. If the file already exists, its contents will be erased. - Error Checking:
This checks if the file was successfully opened. If not, an error message is displayed.
- User Input:
This reads a line of text from standard input into the
data
array. - Write to File:
This writes the contents of
data
to the file. - Close File:
This closes the file after writing.
- Open File:
Reading from a File:
- Open File:
This opens the file in read mode.
- Error Checking: Similar to the write mode, it checks if the file opened successfully.
- Read and Print:
This reads lines from the file and prints them to the console until the end of the file is reached.
- Close File: Again, the file is closed after reading.
- Open File:
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code:Execute the Program:
Example Output
When you run the program, it will prompt you to enter some text, then it will write that text to a file and read it back:
Conclusion
This program demonstrates basic file handling in C, including writing to and reading from a text file. Understanding file operations is essential for developing applications that require data persistence, such as saving user settings, logging events, or processing larger datasets. With these basic concepts, you can extend your file handling skills to include more complex operations like binary file reading/writing, file appending, and handling different file formats.