Home > Backend Development > C++ > How to rename a file using C++?

How to rename a file using C++?

王林
Release: 2024-06-05 22:08:59
Original
854 people have browsed it

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 rename a file using C++?

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);
Copy after login

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:

  1. Contains <iostream> and <cstdio> header files.
  2. Use std::cout to output the file path before renaming.
  3. Use the rename() function to rename the file.
  4. Use 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;
}
Copy after login

Running results

Running the above code will output the following:

旧文件名:oldfile.txt
新文件名:newfile.txt
Copy after login

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.
  • If newname already exists, the rename() function will fail and return -1.
  • In Windows, the 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template