File Handling

 File Handling

File handling is an important feature of the C programming language that allows a program to read and write data to and from files. Here is a brief overview of file handling in C:
https://endtakecode.blogspot.com/?m=1



1.Opening a file: In order to read from or write to a file, you must first open it using the fopen() function. This function takes two arguments: the name of the file and the mode in which it should be opened (read, write, append, etc.). For example, to open a file called "example.txt" for reading, you would use the following code:
                               
FILE *fp;
fp = fopen("example.txt", "r");

2.  Reading from a file: Once you have opened a file, you can read data from it using functions like fscanf() or fgets(). For example, to read a string from a file using fgets(), you could use the following code:

char str[50];
fgets(str, 50, fp);

3.  Writing to a file: To write data to a file, you can use functions like fprintf() or fputs(). For example, to write a string to a file using fputs(), you could use the following code:

char str[ ] = "Hello, world!";
fputs(str, fp);

4. Closing a file: When you are done reading from or writing to a file, you should close it using the fclose() function. For example:

fclose(fp);
                                     
Note that file handling in C can be a bit more complex than this, and there are many more functions and options available. It is important to read the documentation carefully and handle errors properly to ensure that your program works as intended.

Defining and opening file:-

1. Define a file pointer variable of type FILE. For example:                        

FILE *fp;

2. Use the fopen() function to open a file in a specific mode (read, write, append, etc.) and associate it with the file pointer variable. The fopen() function takes two arguments: the name of the file and the mode in which it should be opened. For example, to open a file named "example.txt" for writing, you could use:

fp = fopen("example.txt", "w");
This will create a new file if it does not exist, or truncate the file if it does exist.

3.  Once the file is open, you can read from or write to it using functions like fscanf(), fgets(), fprintf(), fputs(), etc. For example, to write a string to the file, you could use:

char str[ ] = "Hello, world!";
fputs(str, fp);

4.  When you are done with the file, close it using the fclose() function. For example:

fclose(fp);

This will ensure that any pending data is written to the file and any resources used by the file are released.

Note that it is important to handle errors properly when opening and using files. You should always check the return value of fopen() and other file-related functions for errors and take appropriate action.

closing a file:-

In C programming language, you can close a file using the fclose() function. Here's how you can close a file:

1 Make sure you have a file pointer variable associated with the file that you want to close. For example:

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

2. Use the fclose() function to close the file associated with the file pointer variable. For example:

fclose(fp);

This will close the file and free any resources associated with it.

Note that it is important to close the file when you are done with it, as leaving it open can cause issues with other programs that may try to access the same file. Additionally, if you don't close the file, any data that you have written to it may not be saved properly.

I/O operations on file :-

In C programming language, you can perform input/output (I/O) operations on files using functions like fscanf(), fgets(), fprintf(), fputs(), etc. Here's how you can perform basic I/O operations on a file:

1. Define a file pointer variable of type FILE and open the file using the fopen() function. For example:

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

2Use functions like fputs() or fprintf() to write data to the file. For example:

char str[ ] = "Hello, world!";
fputs(str, fp);
fprintf(fp, "%d", 123);

3Use functions like fgets() or fscanf() to read data from the file. For example:

char str[50];
fgets(str, 50, fp);
int num;
fscanf(fp, "%d", &num);

4When you are done with the file, close it using the fclose() function. For example:

fclose(fp);

This closes the file and frees any resources associated with it.

Note that it is important to handle errors properly when performing I/O operations on files. You should always check the return value of file-related functions for errors and take appropriate action. Additionally, you should be careful when reading or writing data to files to ensure that the data is in the correct format and that you do not accidentally overwrite or corrupt existing data in the file.

Random access to file:-

To perform random access to a file in C language with a short word, you can use the fseek() and ftell() functions provided by the standard C library. Here's an example:

#include <stdio.h>

int main() {
    FILE* fp = fopen("myfile.txt", "r+");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    // Seek to the 10th short word in the file
    int word_size = sizeof(short);
    int word_index = 10;
    fseek(fp, word_size * word_index, SEEK_SET);

    // Write a new short word at that position
    short new_word = 12345;
    fwrite(&new_word, sizeof(short), 1, fp);

    // Seek back to the beginning of the file
    fseek(fp, 0, SEEK_SET);

    // Read and print all the short words in the file
    short buffer;
    while (fread(&buffer, sizeof(short), 1, fp) == 1) {
        printf("%d\n", buffer);
    }

    fclose(fp);
    return 0;
}

In this example, we open the file "myfile.txt" in read-write mode ("r+") and check that it was opened successfully. We then use fseek() to move the file pointer to the 10th short word in the file (assuming each short is two bytes long), and use fwrite() to write a new short word at that position. We then use fseek() again to move the file pointer back to the beginning of the file, and use fread() to read and print all the short words in the file. Finally, we close the file with fclose().

Error handling in file :-

When working with files in C language, it is important to handle errors that may occur during file I/O operations. Here's an example of error handling in file I/O operations for short words in C language:

#include <stdio.h>

int main() {
    FILE* fp = fopen("myfile.txt", "r+");
    if (fp == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    // Seek to the 10th short word in the file
    int word_size = sizeof(short);
    int word_index = 10;
    if (fseek(fp, word_size * word_index, SEEK_SET) != 0) {
        printf("Error seeking to position\n");
        fclose(fp);
        return 1;
    }

    // Write a new short word at that position
    short new_word = 12345;
    if (fwrite(&new_word, sizeof(short), 1, fp) != 1) {
        printf("Error writing to file\n");
        fclose(fp);
        return 1;
    }

    // Seek back to the beginning of the file
    if (fseek(fp, 0, SEEK_SET) != 0) {
        printf("Error seeking to beginning of file\n");
        fclose(fp);
        return 1;
    }

    // Read and print all the short words in the file
    short buffer;
    while (fread(&buffer, sizeof(short), 1, fp) == 1) {
        printf("%d\n", buffer);
    }

    if (ferror(fp)) {
        printf("Error reading from file\n");
        fclose(fp);
        return 1;
    }

    fclose(fp);
    return 0;
}

In this example, we handle errors that may occur during file I/O operations by checking the return values of the functions we use. If an error occurs, we print an error message and close the file with fclose(). We also use ferror() to check if there was an error during reading from the file.

Note that ferror() returns non-zero if an error occurred during the last I/O operation on the given file stream, so we need to call it after the loop that reads from the file.


Post a Comment

Previous Post Next Post