Course contentsShow
← C
Lesson 756 of 1,21910. Input and OutputFree lesson

Renaming files with rename

Renaming files with rename

What you'll learn: How to use the C standard library to programmatically change a file's name or move it to a new directory.

Giving a File a New Identity

In your operating system, you often right-click a file to rename it. In C, we do this using the rename function, which is found in the <stdio.h> header.

Think of a file like a physical folder in a filing cabinet. The "name" is just a label written on the tab. When you use rename, you aren't changing the contents of the folder; you are simply erasing the old label and writing a new one. If you provide a different folder path as part of the new name, it’s like picking up the folder and sliding it into a different drawer.

The Syntax

The rename function takes two strings: the current name (the source) and the new name (the destination).

#include <stdio.h>

int main() {
    char old_name[] = "draft_v1.txt";
    char new_name[] = "final_report.txt";

    // rename returns 0 on success
    if (rename(old_name, new_name) == 0) {
        printf("File renamed successfully.\n");
    } else {
        // If the file doesn't exist or permissions are denied
        perror("Error renaming file");
    }

    return 0;
}

How It Behaves

There are a few important rules to keep in mind when using this function:

  1. Success and Failure: The function returns 0 if it works. If it fails (for example, if the original file doesn't exist), it returns a non-zero value.
  2. Overwriting: If a file with the "new name" already exists, the behavior depends on your operating system. Usually, rename will silently delete the existing file and replace it with your renamed one. It is like putting a new folder exactly where an old one was—the old one gets tossed out.
  3. Moving Files: You can use rename to move a file across directories on the same disk drive (e.g., from data/old.txt to archive/old.txt). However, it generally won't work if you try to move a file from one physical drive to another (like from a hard drive to a USB stick).

Key takeaway

Use rename("old.txt", "new.txt") to change a file's name or location, always checking the return value to ensure the operation succeeded.