C File Handling

Using standard I/O library to handle files in C.

fopen() Function:

This function is used to open a file. It takes two arguments: the name of the file you want to open and the mode in which you want to open it (e.g., read, write, append, etc.). It returns a file pointer, which is a data structure that allows you to read from or write to the file.

For reading syntax:

FILE *fp = fopen("example.txt", "r");

For writing syntax:

FILE *fp = fopen("example.txt", "w");

The following "mode" are used in data processing:

  1. "r" (Read): Open for reading. The file is opened for reading, and if the file doesn't exist, the operation will fail.

  2. "w" (Write): Open for writing. If the file exists, it is truncated to zero length. If the file does not exist, a new empty file is created.

  3. "a" (Append): Open for writing, but if the file exists, data is appended to the end of it rather than overwriting the existing content. If the file doesn't exist, a new file is created.

  4. "rb" (Read Binary): Open for reading in binary mode. Similar to "r", but for binary files.

  5. "wb" (Write Binary): Open for writing in binary mode. Similar to "w", but for binary files.

  6. "ab" (Append Binary): Open for writing in binary mode with appending. Similar to "a", but for binary files.

  7. "r+" (Read/Write): Open for both reading and writing. The file must exist, but you can both read and write to it.

  8. "w+" (Write/Read): Open for both reading and writing. If the file exists, it is truncated. If it doesn't exist, a new file is created.

  9. "a+" (Append/Read): Open for both reading and writing, with appending. If the file exists, data is appended; if not, a new file is created.

  10. "r+b" or "rb+" (Read/Write Binary): Open for both reading and writing in binary mode. Similar to "r+", but for binary files.

  11. "w+b" or "wb+" (Write/Read Binary): Open for both reading and writing in binary mode. Similar to "w+", but for binary files.

  12. "a+b" or "ab+" (Append/Read Binary): Open for both reading and writing in binary mode with appending. Similar to "a+", but for binary files.

fclose() Function:

This function is used to close a file that was previously opened with 'fopen()'. It takes a single argument, which is the file pointer associated with the file you want to close.

Syntax for closing:

fclose(fp);

feof() Function:

This function is used to check whether the end of a file has been reached. It takes a file pointer as its argument and returns a non-zero value if the end of the file has been reached, or 0 if it hasn't.

Syntax:

if (feof(file)) {
    // End of file has been reached
} else {
    // End of file has not been reached
}

* The 'fread()', 'fwrite()', 'fscanf()', and 'fprintf()' are functions used for file input and output operations. They are part of the standard I/O library and are used for reading from and writing to files. Here's an overview of each function:

fread() Function:

This function is used for reading binary data from a file. It is typically used when you want to read data in its raw binary format. The function takes four arguments: a pointer to a buffer where the data will be stored, the size of each element to be read, the number of elements to read, and a file pointer to the input file.

Syntax:

FILE* file = fopen("data.bin", "rb");
if (file != NULL) {
    int data[10];
    fread(data, sizeof(int), 10, file);
    fclose(file);
}

fwrite() Function:

This function is used for writing binary data to a file. It is the counterpart of 'fread()'. It takes four arguments: a pointer to the data to be written, the size of each element, the number of elements to write, and a file pointer to the output file.

Syntax:

FILE* file = fopen("data.bin", "rb");
if (file != NULL) {
    int data[10];
    fread(data, sizeof(int), 10, file);
    fclose(file);
}

fscanf() Function:

This function is used for reading data from a text file. It allows you to read formatted data from the file based on a specified format string. The function takes a file pointer and format string followed by a list of pointers to variables where the read data will be stored.

Syntax:

FILE* file = fopen("data.txt", "r");
if (file != NULL) {
    int value;
    fscanf(file, "%d", &value);
    fclose(file);
}

fprintf() Function:

This function is used for writing data to a text file, just like printf(). It allows you to format data and write it to the file. The function takes a file pointer and a format string, followed by a list of values to be written to the file based on the format string.

Syntax:

FILE* file = fopen("data.txt", "w");
if (file != NULL) {
    int value = 42;
    fprintf(file, "The value is: %d\n", value);
    fclose(file);
}

Handling Characters

The 'getc()' and 'putc()' functions are used to read and write characters from/to a file. These functions are part of the Standard I/O Library, which provides a convenient way to perform file I/O operations. Here's how you can use these functions to handle a file:

  • Reading from a File using 'getc()':

The 'getc()' function reads a character from a file. You can use it in a loop to read characters from a file until the end of the file is reached. Here's an example:

c Copy Code
#include <stdio.h>

int main() {
    FILE *file;
    char ch;

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

    if (file == NULL) {
        printf("Unable to open the file.\n");
        return 1;
    }

    // Read and print characters from the file
    while ((ch = getc(file)) != EOF) {
        printf("%c", ch);
    }

    // Close the file
    fclose(file);

    return 0;
}
Output:
The file opened & read successfully.

* In this example, we open a file named "example.txt" for reading using 'fopen()', then we use a 'while' loop to read characters from the file until 'EOF' (end of file) is reached. We print the characters to the console.

  • Writing to a File using 'puts()':

The 'puts()' function is used to write a string to a file. Here's an example:

c Copy Code
#include <stdio.h>

int main()
{
    char str[] = "Hello, World!";
    FILE *file = fopen("output.txt", "w"); // Open the file for writing

    if (file == NULL)
    {
        perror("Error opening file");
        return 1;
    }

    for(int i; str[i] != '\0'; i++)
    {
        if (putc(str[i], file) == EOF)
        {
            perror("Error writing to file");
            return 1;
        }
    }

    fclose(file); // Close the file

    return 0;
}

* In this example, we open a file named "output.txt" for writing, and we insert the string "Hello, World!" into the file character by character using a loop. Each character in the string is written to the file using the 'putc()' function.

Handling Integers

The the 'getw()' and 'putw()' functions are used for reading and writing binary data to and from files, respectively. These functions are typically used for handling binary data rather than text data.

  • Reading binary integer 'getw()':

The 'getw()' function is used to read a binary integer from a file.

int getw(FILE *stream);

The 'getw()' function reads an integer from the specified 'stream' and returns its value. It reads binary data, so it's typically used to read data written by 'putw()' or similar functions.

c Copy Code
#include <stdio.h>

int main() {
// Open a binary file for reading
    FILE *file = fopen("data.bin", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

// Read an integer from the file
    int value = getw(file);
    printf("Read value: %d\n", value);

    fclose(file); // Close the file
    return 0;
}
  • Writing binary integer 'putw()':

The 'putw()' function is used to write a binary integer to a file.

int putw(int w, FILE *stream);

The 'putw()' function writes the binary representation of the integer 'w' to the specified 'stream'. It's typically used to write binary data to a file.

c Copy Code
#include <stdio.h>

int main() {
    FILE *file = fopen("data.bin", "wb"); // Open a binary file for writing
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    int value = 42;
    putw(value, file); // Write an integer to the file

    fclose(file); // Close the file
    return 0;
}

Note: The 'getw()' and 'putw()' both functions are not part of the standard C library.

What is New?

We have just updated this website & still working on adding new content & updating existing features.