Deleting or Renaming a File in C

The C language standard library provides some simple functions to work with files at the operating system level, including the ability to delete or rename a file.

Unfortunately, there are no functions to work on directories, so more complex operations such as creating or removing directories require the use of functions specific to the operating system in use.

In this lesson we will see how to delete or rename a file using the remove() and rename() functions. These functions are declared in the <stdio.h> header file and, unlike the functions for opening, reading, writing and closing files, do not require the use of pointers to objects of type FILE but operate directly on character strings that represent file names.

Key Takeaways
  • The C language standard library provides the remove() and rename() functions to delete or rename a file at the operating system level.
  • The remove() function deletes a file specified by name.
  • The rename() function renames a file from an original name to a specified new name.
  • Both functions return 0 on success and -1 on error.
  • It is important to ensure that the file is not open when using these functions.

Deleting a file

To delete a file in C language, the remove() function is used, whose syntax is as follows:

int remove(const char *filename);

The function requires as a parameter a character string (const char *filename) that represents the name of the file to be deleted. It returns an integer value: 0 if the file deletion was successful, or -1 in case of error (for example, if the file does not exist or you do not have the necessary permissions to delete it).

This function is particularly useful when you want to remove a temporary file created during program execution. For example, as we saw in that lesson, when we use the tmpnam() function to generate a temporary file name, we can subsequently delete that file using remove():

#include <stdio.h>
#include <stdlib.h>

int main() {
    char filename[L_tmpnam];
    FILE *tempFile;

    // Generate a temporary file name
    tmpnam(filename);

    // Create the temporary file
    tempFile = fopen(filename, "wb+");
    if (tempFile == NULL) {
        printf("Error in creating the temporary file\n");
        return EXIT_FAILURE;
    }

    // Work with the temporary file
    // ...

    // Close the temporary file
    fclose(tempFile);
    // Delete the temporary file
    if (remove(filename) != 0) {
        printf("Error in deleting the temporary file\n");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

In this example, after creating and using a temporary file, we close it with fclose() and then delete it with remove(). This would not have been necessary if we had used the tmpfile() function, which creates a temporary file that is automatically deleted upon closing.

When using the remove() function, it is important to keep the following warning in mind:

Note

You must ensure that the file is not open when using remove()

If you attempt to delete a file that is currently open in a program, the behavior of the remove() function depends on the operating system. In many cases, deleting an open file may fail, returning an error. Therefore, it is good practice to ensure that the file is closed (using fclose()) before calling remove().

Renaming a file

To rename a file in C language, the rename() function is used, whose syntax is as follows:

int rename(const char *oldFilename, const char *newFilename);

The function requires as parameters two character strings: oldFilename, which represents the current name of the file, and newFilename, which represents the new name you want to assign to the file. It returns an integer value: 0 if the operation was successful, or -1 in case of error (for example, if the original file does not exist or if the new name is already in use).

This function is particularly useful when you want to rename a temporary file created during program execution so that it becomes permanent. For example, after creating and working with a temporary file, we can decide that it should be saved with a definitive name:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char tempFilename[L_tmpnam];
    char finalFilename[] = "final_data.dat";
    FILE *tempFile;

    // Generate a temporary file name
    tmpnam(tempFilename);

    // Create the temporary file
    tempFile = fopen(tempFilename, "wb+");
    if (tempFile == NULL) {
        printf("Error in creating the temporary file\n");
        return EXIT_FAILURE;
    }

    // Work with the temporary file
    // ...

    // Close the temporary file
    fclose(tempFile);
    // Rename the temporary file to a definitive name
    if (rename(tempFilename, finalFilename) != 0) {
        printf("Error in renaming the file\n");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

In this example, after creating and using a temporary file, we close it with fclose() and then rename it to final_data.dat using rename().

Also in this case, it is important to keep the following warning in mind:

Note

You must ensure that the file is not open when using rename()

If you attempt to rename a file that is currently open in a program, the behavior of the rename() function depends on the operating system. In many cases, the operation may fail, returning an error. Therefore, it is good practice to ensure that the file is closed (using fclose()) before calling rename().

Furthermore, you must also ensure that the specified new name is not already in use by another file, otherwise the operation is undefined and may lead to data loss:

Note

Avoid renaming a file to an already existing name

When using the rename() function, it is important to verify that the specified new name is not already in use by another file. If the new name already exists, the rename operation may lead to data loss, as the original file may be overwritten or deleted depending on the operating system. Therefore, it is good practice to check the existence of the file with the new name before proceeding with the rename.