Home > Article > Backend Development > How to rename a file using C++?
In C++, use the rename() function to rename a file or directory. The syntax is int rename(const char oldname, const char newname);, where oldname is the original name and newname is the new name. The specific steps include: 1. Include the header file; 2. Output the path before renaming; 3. Rename using the rename() function; 4. Output the path after renaming.
How to use C++ to rename files
Preface
File renaming is A common task in document management. In C++, files can be easily renamed using the rename()
function. This article will introduce how to use the rename()
function and provide practical case illustrations.
rename()
Function
rename()
Function is used to rename one file or directory to another name. Its prototype is as follows:
int rename(const char *oldname, const char *newname);
Where:
oldname
: The path of the original file or directory to be renamed. newname
: The path to the new file or directory. Practical case
To use the rename()
function to rename a file, you can use the following steps:
<iostream></iostream>
and <cstdio></cstdio>
header files. std::cout
to output the file path before renaming. rename()
function to rename the file. std::cout
to output the file path after renaming. The following code demonstrates how to use the rename()
function to rename a file:
#include <iostream> #include <cstdio> int main() { // 输出重命名之前的文件路径 std::cout << "旧文件名:oldfile.txt\n"; // 重命名文件 rename("oldfile.txt", "newfile.txt"); // 输出重命名之后的文件路径 std::cout << "新文件名:newfile.txt\n"; return 0; }
Running results
Running the above code will output the following:
旧文件名:oldfile.txt 新文件名:newfile.txt
Notes
When using the rename()
function, you need to pay attention to the following when renaming a file:
oldname
and newname
must be valid paths. newname
already exists, the rename()
function will fail and return -1. rename()
function requires administrator privileges to rename a protected file or directory. The above is the detailed content of How to rename a file using C++?. For more information, please follow other related articles on the PHP Chinese website!