w3resource

C File Handling: fopen(), fclose(), fread(), and fwrite() Tutorial

C Programming - File Handling

Overview:

File handling in C is essential for reading from and writing to files, allowing programs to manage data efficiently. This tutorial covers the core functions used for file operations: fopen(), fclose(), fread(), and fwrite(). We will demonstrate their usage with practical examples and detailed explanations.

Key Topics:

fopen() Function - Opening a file in C

The fopen() function is used to open a file in C. It creates a new file if it doesn't exist (depending on the mode) or opens an existing file for reading, writing, or both. It returns a pointer to the file (of type FILE *). If the file cannot be opened, it returns NULL.

Syntax of fopen() Function in C

FILE* fopen(const char* filename, const char* mode);

Parameters:

  • filename:
    • Description: A string representing the name (or path) of the file to be opened.
    • Type: const char* (pointer to a string).
    • Example: "example.txt"
  • mode:
    • Description: A string representing the mode in which the file should be opened. Common modes include reading, writing, appending, etc.
    • Type: const char* (pointer to a string).
    • Example: "r" for reading, "w" for writing.

Common File Modes:

  • "r": Opens the file for reading. The file must exist.
  • "w": Opens the file for writing. If the file exists, its contents are erased. If the file does not exist, it is created.
  • "a": Opens the file for appending. Data is written at the end of the file. If the file does not exist, it is created.
  • "r+": Opens the file for both reading and writing. The file must exist.
  • "w+": Opens the file for both reading and writing. If the file exists, its contents are erased. If it doesn’t exist, a new file is created.
  • "a+": Opens the file for both reading and appending. If the file does not exist, it is created.

Return Value:

  • Returns a pointer of type FILE* that represents the opened file.
  • If the file cannot be opened, fopen() returns NULL.

Example:

Code:

FILE *file;
file = fopen("example.txt", "r");
if (file == NULL) {
    printf("Error: Could not open file.\n");
} else {
    // Proceed with reading or writing to the file
    fclose(file); // Close the file after usage
}

Key Points:

  • Always check the return value to ensure the file was opened successfully.
  • After finishing file operations, use fclose() to close the file and free resources.

fclose() Function - Closing a File in C

The fclose() function is used to close a file that was previously opened using fopen(), freopen(), or other file-opening functions. It ensures that any data still in the buffer is flushed to the file and that system resources (such as file pointers) are properly released.

Syntax of fclose() Function in C

int fclose(FILE* stream);

Parameters:

  • stream:
    • Description: A pointer to the file object that was opened by fopen(). This is the file that you want to close.
    • Type: FILE*
    • Example: If you opened a file like FILE *file = fopen("example.txt", "r");, then you would pass file to fclose().

Return Value:

  • Returns 0 if the file is closed successfully.
  • Returns EOF (End of File) if an error occurs during closing.

Example:

Code:

FILE *file;
// Open a file for reading
file = fopen("example.txt", "r");

if (file == NULL) {
    printf("Error: Could not open file.\n");
} else {
    // Perform file operations
    // Close the file after usage
    if (fclose(file) == 0) {
        printf("File closed successfully.\n");
    } else {
        printf("Error: Could not close the file.\n");
    }
}

Key Points:

  • Always close files after you're done working with them to free resources.
  • Closing a file ensures that any buffered data is written to disk (especially important when writing to a file).
  • Failing to close a file can lead to memory leaks or corruption of the file.

fread() Function - Reading from a File in C

The fread() function is used to read a block of data from a file into memory. It reads binary data from a file stream, which makes it suitable for working with both text and binary files.

Syntax of fread() Function in C

size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream);

Parameters:

  • ptr:
    • Description: A pointer to the memory where the data read from the file will be stored.
    • Type: void*
    • Example: char buffer[50]; fread(buffer, sizeof(char), 50, file);
  • size:
    • Description: The size of each element to be read, in bytes. Typically, this is the sizeof() the data type being read (e.g., sizeof(int) or sizeof(char)).
    • Type: size_t
    • Example: sizeof(int) when reading integers or sizeof(char) when reading characters.
  • nmemb:
    • Description: The number of elements to read. This specifies how many items of the given size should be read from the file.
    • Type: size_t
    • Example: To read 100 integers from a file, use fread(array, sizeof(int), 100, file);.
  • stream:
    • Description: A pointer to the FILE object from which to read the data. This is the file that was opened using fopen().
    • Type: FILE*
    • Example: If you opened a file with FILE *file = fopen("data.bin", "rb");, pass file as the stream.

Return Value:

  • Return Type: size_t
  • Description: The total number of elements successfully read. If this value is less than nmemb, either the end of the file has been reached, or an error occurred.

Example:

Code:

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *file;
    int buffer[5]; // Array to hold the data read from the file

    // Open the file in binary read mode
    file = fopen("data.bin", "rb");

    if (file == NULL) {
        printf("Error: Could not open file.\n");
        return 1;
    }

    // Read 5 integers from the file
    size_t elementsRead = fread(buffer, sizeof(int), 5, file);

    // Check if the correct number of elements was read
    if (elementsRead == 5) {
        printf("Data read from the file:\n");
        for (int i = 0; i < 5; i++) {
            printf("%d ", buffer[i]);
        }
        printf("\n");
    } else {
        printf("Error: Could not read the expected amount of data.\n");
    }

    // Close the file
    fclose(file);

    return 0;
}

Key Points

  • fread() reads data in binary form, making it suitable for any type of file.
  • The function reads data into memory pointed to by ptr.
  • Always check the return value to ensure the desired amount of data was read.
  • EOF (End of File) can cause fread() to return fewer elements than requested without an error occurring.

fwrite() Function - Writing to a File in C

The fwrite() function is used to write data from memory to a file. It is commonly used for writing binary data to files but can also write text data. The function writes a specified number of elements of a given size from a buffer to a file stream.

Syntax of fwrite() Function in C

size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream);

Parameter:

  • ptr:
    • Description: A pointer to the array or memory block where the data to be written is stored.
    • Type: const void*
    • Example: int arr[5]; fwrite(arr, sizeof(int), 5, file);
  • size:
    • Description: The size of each element to write, in bytes. Usually, this is the sizeof() the data type being written (e.g., sizeof(int) or sizeof(char)).
    • Type: size_t
    • Example: sizeof(int) when writing integers or sizeof(char) when writing characters.
  • nmemb:
    • Description: The number of elements to write. This parameter specifies how many items of the given size should be written from memory to the file.
    • Type: size_t
    • Example: To write 100 integers to a file, use fwrite(array, sizeof(int), 100, file);.
  • stream:
    • Description: A pointer to the FILE object representing the open file where data is written. This file is typically opened using fopen().
    • Type: FILE*
    • Example: If you opened a file with FILE *file = fopen("data.bin", "wb");, pass file as the stream.

Return Value:

  • Return Type: size_t
  • Description: The total number of elements successfully written. If this value is less than nmemb, it indicates an error occurred or that the disk is full.

Example:

Code:

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *file;
    int arr[5] = {1, 2, 3, 4, 5}; // Data to write to the file

    // Open the file in binary write mode
    file = fopen("data.bin", "wb");

    if (file == NULL) {
        printf("Error: Could not open file for writing.\n");
        return 1;
    }

    // Write 5 integers from arr to the file
    size_t elementsWritten = fwrite(arr, sizeof(int), 5, file);

    // Check if the correct number of elements was written
    if (elementsWritten == 5) {
        printf("Data successfully written to the file.\n");
    } else {
        printf("Error: Could not write the expected amount of data.\n");
    }

    // Close the file
    fclose(file);

    return 0;
}

Key Points:

  • fwrite() writes data in binary form, which makes it suitable for writing any type of data (text or binary).
  • The function writes data from memory pointed to by ptr to the file specified by stream.
  • Always check the return value to ensure that the correct number of elements was written.
  • If fwrite() writes fewer elements than expected, it usually indicates a problem with the file system, such as insufficient disk space.

Example - Opening and Closing Files with fopen() and fclose()

Following example demonstrates how to open and close a file using the fopen() and fclose() function.

Code:

#include <stdio.h>
int main() {
    FILE *file; // Pointer to a file
    // Open a file for writing ("w" mode)
    file = fopen("example.txt", "w");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Write a message to the file
    fprintf(file, "Hello, World!\n");

    // Close the file
    fclose(file);

    return 0;
}

Explanation:

  • fopen("example.txt", "w") opens the file example.txt for writing. If the file does not exist, it is created. If it exists, its contents are truncated.
  • fclose(file) closes the file, ensuring that all data is flushed and resources are freed.

Key Points:

  • Always check if fopen() returns NULL, indicating an error.
  • Always close files with fclose() to avoid memory leaks and ensure data integrity.

Example - Reading from Files with fread()

Following example demonstrates how to read text data from a file using the fread() function.

Code:

#include <stdio.h>

int main() {
    FILE *file;
    char buffer[20];  // Buffer to store data

    // Open a file for reading ("r" mode for text files)
    file = fopen("example.txt", "r");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Read data from the file into the buffer
    size_t bytesRead = fread(buffer, sizeof(char), sizeof(buffer) - 1, file);
    buffer[bytesRead] = '\0';  // Null-terminate the string

    // Check if the read operation was successful
    if (bytesRead > 0) {
        // Print the read text
        printf("Data read from file: %s\n", buffer);
    } else {
        printf("Error reading data!\n");
    }

    // Close the file
    fclose(file);

    return 0;
}

Output:

Data read from file: Hello, World!

Explanation:

  • fopen("example.txt", "r") opens a text file for reading in text mode.
  • fread(buffer, sizeof(char), sizeof(buffer) - 1, file) reads up to 19 characters from the file into the buffer.
  • A null terminator is added to the buffer to create a valid string.
  • The program checks if data was read successfully and prints the result.

Example - Writing to Files with fwrite()

Following example focuses on writing text data to a file using fwrite() in a text file format.

Code:

#include <stdio.h>
int main() {
    FILE *file;
    const char *text = "Hello, World!";

    // Open a file for writing ("w" mode)
    file = fopen("output.txt", "w");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    // Write data to the file
    size_t elements_written = fwrite(text, sizeof(char), 13, file);

    // Check if the write operation was successful
    if (elements_written < 13) {
        printf("Error writing data!\n");
    } else {
        printf("Data written successfully!\n");
    }

    // Close the file
    fclose(file);

    return 0;
}

Output:

Data written successfully!

Explanation:

  • fopen("output.txt", "w") opens the file output.txt in write mode.
  • fwrite(text, sizeof(char), 13, file) writes 13 characters (including space and punctuation) from the text string into the file.
  • After the writing operation, the program checks whether the correct number of elements was written.
  • The file is then closed using fclose().

Summary of File Handling Functions

  • fopen(): Opens a file. Returns NULL if the file cannot be opened.
  • fclose(): Closes an open file.
  • fread(): Reads data from a file. Returns the number of items read.
  • fwrite(): Writes data to a file. Returns the number of items written.
  • free(): Frees allocated memory.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/c-file-handling.php