C Programming Tutorial

C Programming Tutorial

Basic of File Handling in C

Hello Everyone, In this article, we will discuss Basic of File Handling in C. You will learn how to open, read, write, and close files using C programming. Understanding file handling is essential for managing data storage and retrieval in your programs. Whether you are new to C or have some experience, this guide will help you to understand basics of File Handling in C effectively with examples. Let’s get started.

In C programming, file input/output (I/O) refers to the ability to read data from and write data to files. This is important because it allows programs to store and retrieve data that can persist even after the program has ended.

To perform file I/O in C, you first need to open a file using the fopen() function. This function takes two arguments: the name of the file you want to open, and a string that specifies the mode in which you want to open the file (e.g., “r” for read, “w” for write, “a” for append, etc.).

Once you have opened a file, you can read data from it using functions like fgetc() and fgets(), or you can write data to it using functions like fputc() and fputs(). When you are finished working with a file, you should close it using the fclose() function.

Here is an example of how you might use file I/O in C to read data from a file:

arduinoCopy code
#include <stdio.h>int main() {
    FILE *fp;
    char buffer[255];

    fp = fopen("myfile.txt", "r");
    if (fp == NULL) {
        printf("Failed to open file\\n");
        return 1;
    }

    fgets(buffer, 255, fp);
    printf("The first line of the file is: %s\\n", buffer);

    fclose(fp);
    return 0;
}

In this example, we open a file called “myfile.txt” for reading using fopen(). We then use fgets() to read the first line of the file into a buffer, which we then print to the console. Finally, we close the file using fclose().

In C programming, there are several operations that you can perform on file input/output (I/O). These operations include:

  1. Opening a file: To perform file I/O in C, you first need to open a file using the fopen() function. This function takes two arguments: the name of the file you want to open, and a string that specifies the mode in which you want to open the file (e.g., “r” for read, “w” for write, “a” for append, etc.).
  2. Reading from a file: Once you have opened a file, you can read data from it using functions like fgetc() and fgets(). These functions allow you to read one character or one line of text at a time, respectively. Alternatively, you can use fread() to read a specified number of bytes at once.
  3. Writing to a file: You can write data to a file using functions like fputc() and fputs(). These functions allow you to write one character or one line of text at a time, respectively. Alternatively, you can use fwrite() to write a specified number of bytes at once.
  4. Closing a file:When you are finished working with a file, you should close it using the fclose() function. This is important because it ensures that any data that is still in the buffer is written to the file before it is closed.
  5. Checking for errors: When performing file I/O in C, it is important to check for errors using functions like feof() and ferror(). These functions allow you to determine whether the end of the file has been reached or whether an error has occurred during the I/O operation, respectively.
  6. Positioning in a file: You can move the file pointer to a specific position in a file using functions like fseek() and ftell(). This allows you to read or write data from a specific location in the file.
  7. Truncating a file: You can truncate a file to a specific size using the ftruncate() function. This allows you to remove data from the end of a file, effectively reducing its size.
FunctionDescription
fopen()Opens a file with a specified name and mode. Returns a pointer to a FILE object that can be used for reading or writing to the file.
fclose()Closes a file that was previously opened with fopen(). Any data that is still in the buffer is written to the file before it is closed.
fgets()Reads a line of text from a file into a buffer. Stops reading when a newline character is encountered or when the buffer is full.
fread()Reads a specified number of bytes from a file into a buffer.
fgetc()Reads a single character from a file.
fputc()Writes a single character to a file.
fwrite()Writes a specified number of bytes from a buffer to a file.
fputs()Writes a line of text from a buffer to a file.
feof()Returns a non-zero value if the end of the file has been reached.
ferror()Returns a non-zero value if an error has occurred during a file I/O operation.
fseek()Moves the file pointer to a specified position in the file.
ftell()Returns the current position of the file pointer in the file.
ftruncate()Truncates a file to a specified size.
remove()Deletes a file with a specified name.

In C programming, there are several access modes that you can use when opening a file using the fopen() function. These modes determine how you can read from or write to the file. The available access modes are:

  1. “r”: This mode is used for reading an existing file. If the file does not exist, the fopen() function will return NULL.
  2. “w”: This mode is used for writing to a file. If the file already exists, its contents will be truncated (i.e., deleted). If the file does not exist, a new file will be created.
  3. “a”: This mode is used for appending to an existing file. If the file does not exist, a new file will be created.
  4. “r+”: This mode is used for reading and writing to an existing file. If the file does not exist, the fopen() function will return NULL.
  5. “w+”: This mode is used for reading and writing to a file. If the file already exists, its contents will be truncated (i.e., deleted). If the file does not exist, a new file will be created.
  6. “a+”: This mode is used for reading and appending to an existing file. If the file does not exist, a new file will be created.

In addition to these access modes, you can also specify whether the file should be opened in binary mode (i.e., “b”) or text mode (i.e., “t”). The default mode is text mode, so you do not need to specify this mode unless you specifically want to open the file in binary mode.

For example, to open a file called “example.txt” for writing in text mode, you would use the following code:

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

Similarly, to open the same file for reading and writing in binary mode, you would use the following code:

makefileCopy code
FILE *fp;
fp = fopen("example.txt", "rb+");

Write a c program to explain all file operations

scssCopy code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    FILE *fp;
    char filename[] = "example.txt";
    char mode[] = "w";
    char buffer[255];

    // Open a file for writing
    fp = fopen(filename, mode);
    if (fp == NULL) {
        printf("Failed to open file\\n");
        return 1;
    }

    // Write some text to the file
    char text[] = "This is an example text";
    fwrite(text, strlen(text), 1, fp);

    // Close the file
    fclose(fp);

    // Open the same file for reading
    fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Failed to open file\\n");
        return 1;
    }

    // Read the text from the file
    fgets(buffer, 255, fp);
    printf("The text in the file is: %s\\n", buffer);

    // Move the file pointer to the beginning of the file
    fseek(fp, 0, SEEK_SET);

    // Read the text from the file again
    fgets(buffer, 255, fp);
    printf("The text in the file is: %s\\n", buffer);

    // Close the file
    fclose(fp);

    // Open the same file for appending
    fp = fopen(filename, "a");
    if (fp == NULL) {
        printf("Failed to open file\\n");
        return 1;
    }

    // Write some more text to the file
    char more_text[] = "This is some additional text";
    fwrite(more_text, strlen(more_text), 1, fp);

    // Close the file
    fclose(fp);

    // Open the file for reading and writing
    fp = fopen(filename, "r+");
    if (fp == NULL) {
        printf("Failed to open file\\n");
        return 1;
    }

    // Move the file pointer to the beginning of the file
    fseek(fp, 0, SEEK_SET);

    // Read the text from the file again
    fgets(buffer, 255, fp);
    printf("The text in the file is: %s\\n", buffer);

    // Write some new text to the file
    char new_text[] = "This is some new text";
    fwrite(new_text, strlen(new_text), 1, fp);

    // Close the file
    fclose(fp);

    // Delete the file
    int status = remove(filename);
    if (status == 0) {
        printf("File deleted successfully\\n");
    } else {
        printf("Failed to delete file\\n");
        return 1;
    }

    return 0;
}

In this program, we first open a file called “example.txt” for writing using the fopen() function. We then write some text to the file using the fwrite() function, and close the file using the fclose() function.

Next, we open the same file for reading, read the text from the file using the fgets() function, and print it to the console. We then move the file pointer to the beginning of the file using the fseek() function, and read the text from the file again. We then close the file using the fclose() function.

After that, we open the same file for appending using the fopen() function, write some more text to the file using the fwrite() function, and close the file using the fclose() function.

Finally, we open the file for reading and writing using the fopen() function, move the file pointer to the beginning of the file using fseek(), read the text from the file again using fgets(), write some new text to the file using fwrite(), and close the file using fclose().

Lastly, we delete the file using the remove() function and print a message to the console indicating whether the deletion was successful or not.

By running this program, you can see how the basic file operations work in C programming. Note that there are many more advanced file operations and techniques that you can use, depending on your specific needs and requirements.

Share This Article