Course Content
C Tutorial
About Lesson

Reading and Writing Text Files

File handling is a crucial aspect of programming, allowing the manipulation of data stored in files. In C programming, reading from and writing to text files is accomplished through a set of functions that facilitate these operations.

Opening a File in C

To perform operations on a file in C, the first step is to open it using the fopen() function. This function takes two arguments: the name of the file and the mode in which the file should be opened (e.g., read, write, append). For instance:

FILE *filePointer;
filePointer = fopen("example.txt", "r"); // Opens the file in read mode

Reading from a Text File

Once a file is opened, you can read its contents using functions like fscanf() or fgets(). These functions allow you to read data from the file and store it in variables. Here’s an example using fgets():

FILE *filePointer;
char data[100];

filePointer = fopen("example.txt", "r");
if (filePointer == NULL) {
// Handle file opening error
} else {
while (fgets(data, 100, filePointer) != NULL) {
printf("%s", data); // Print the read data
}
fclose(filePointer); // Close the file
}

Writing to a Text File

To write data to a text file, you can use functions like fprintf() or fputs(). These functions allow you to write data into the file from variables or strings. Here’s an example using fprintf():

FILE *filePointer;

filePointer = fopen("example.txt", "w");
if (filePointer == NULL) {
// Handle file opening error
} else {
fprintf(filePointer, "This is an example text."); // Write to the file
fclose(filePointer); // Close the file
}

Closing a File in C

It’s essential to close the file once you’re done working with it using the fclose() function. This step is crucial as it frees up resources and ensures that all data is written to the file.

FILE *filePointer;

filePointer = fopen("example.txt", "r");
// Perform read/write operations
fclose(filePointer); // Close the file