Course Content
C Tutorial
About Lesson

Working with Files (fopen, fclose, fread, fwrite)

File handling in C involves a set of essential functions that enable you to work with files, including fopen, fclose, fread, and fwrite. Understanding how to manipulate files in C is fundamental for reading, writing, and managing data. Let’s delve into each function’s role and how they facilitate file operations.

fopen: Opening a File

The fopen function serves as the gateway to access files in C. It’s used to open files, specifying the file name and mode (e.g., read, write, append). Here’s an example:

FILE *filePointer;
filePointer = fopen("example.txt", "r"); // Opens 'example.txt' in read mode
if (filePointer == NULL) {
// Handle error if file doesn't open
}

fclose: Closing a File

Once you’ve finished working with a file, it’s crucial to close it using fclose. This step ensures that resources associated with the file are properly released. For instance:

int status = fclose(filePointer);
if (status == EOF) {
// Handle error in closing the file
}

fread: Reading from a File

The fread function reads data from a file into a buffer. It takes parameters such as the buffer, size of elements to be read, number of elements, and the file pointer. Below is an example demonstrating its usage:

char buffer[100];
size_t elementsToRead = 1; // Read one element
size_t sizeOfElement = sizeof(buffer[0]); // Size of each element

// Read from file into buffer
size_t bytesRead = fread(buffer, sizeOfElement, elementsToRead, filePointer);

if (bytesRead == elementsToRead) {
// Data successfully read
} else {
// Handle error in reading data
}

fwrite: Writing to a File

Conversely, fwrite is used to write data from a buffer into a file. It also requires parameters specifying the buffer, size of elements, number of elements, and the file pointer. Here’s an example:

char buffer[] = "This is a sample text.";
size_t elementsToWrite = sizeof(buffer) - 1; // Exclude null terminator
size_t sizeOfElement = sizeof(buffer[0]); // Size of each element

// Write data from buffer into file
size_t bytesWritten = fwrite(buffer, sizeOfElement, elementsToWrite, filePointer);

if (bytesWritten == elementsToWrite) {
// Data successfully written
} else {
// Handle error in writing data
}