Rename a File using C
To rename a file using C, you can use the rename()
function from stdio.h
, or the system()
function.
Example 1: Renaming a File using rename()
Function
In this example, we will rename a file named oldfile.txt
to newfile.txt
using the standard rename()
function. This function is part of stdio.h
and is straightforward for renaming files in C.
main.c
</>
Copy
#include <stdio.h>
int main() {
// Attempt to rename the file "oldfile.txt" to "newfile.txt"
if (rename("oldfile.txt", "newfile.txt") != 0) {
perror("Error renaming file");
} else {
printf("File renamed successfully.\n");
}
return 0;
}
Explanation:
- The
rename()
function is called with two arguments: the current filename"oldfile.txt"
and the new filename"newfile.txt"
. - The
if
statement checks whether therename()
function returns a non-zero value, which indicates an error. - If an error occurs,
perror()
prints an error message explaining the issue. - If the operation is successful,
printf()
outputs a success message.
Output:
File renamed successfully.
Example 2: Renaming a File using the system()
Function
In this example, we use the system()
function to execute a shell command that renames a file. This approach can be useful in environments where you want to leverage shell commands, though it is less portable than using rename()
.
main.c
</>
Copy
#include <stdio.h>
#include <stdlib.h>
int main() {
// Using system() to rename a file via shell command (works on Unix-like systems)
int status = system("mv oldfile.txt newfile.txt");
if (status != 0) {
printf("Error renaming file using system call.\n");
} else {
printf("File renamed successfully using system call.\n");
}
return 0;
}
Explanation:
- We include
stdlib.h
to use thesystem()
function. - The
system()
function executes the shell command"mv oldfile.txt newfile.txt"
, which renames the file on Unix-like systems. - The returned value is stored in the variable
status
, which is checked for errors. A non-zero value indicates a failure. - If the renaming fails, an error message is printed using
printf()
. Otherwise, a success message is printed.
Output:
File renamed successfully using system call.
Conclusion
This tutorial demonstrated two different approaches to rename a file using C:
rename()
Function: A standard and portable way to rename files, which provides error checking usingperror()
.system()
Function: Executes a shell command (mv
on Unix-like systems) to rename the file, useful in specific environments.