how to delete data and add from file in c language

To delete data from a file and add new data in C language, you can follow these steps:

  1. Open the file: Use the fopen() function to open the file in the desired mode. For deleting data, you need to open the file in write mode, which will clear the existing content. To add new data, you can open the file in append mode, which will keep the existing content and allow adding data at the end.

  2. Delete data (optional): If you want to delete data from the file, you can use the fclose() function to close the file and then reopen it in write mode. This will delete the existing content. However, be cautious as this step is irreversible and will permanently remove the data from the file.

  3. Add new data: Once the file is open in the desired mode, you can use the fprintf() function to write new data to the file. Use the file pointer returned by fopen() to write the data.

  4. Close the file: After you have finished writing the new data, it is important to close the file using the fclose() function. This ensures that any changes made to the file are properly saved.

Here is an example that demonstrates these steps:

#include <stdio.h>

int main() {
    FILE *file = fopen("data.txt", "w"); // Open file in write mode

    if (file == NULL) {
        printf("Error opening the file.\n");
        return 1;
    }

    // Delete data (optional)
    fclose(file);
    file = fopen("data.txt", "w");

    // Add new data
    fprintf(file, "This is a new line of data.\n");

    // Close the file
    fclose(file);

    return 0;
}

In this example, the file "data.txt" is opened in write mode, the content is deleted, and then a new line of data is added. Finally, the file is closed. Make sure to replace "data.txt" with the actual name of the file you want to modify.