C++ 中的rename() 函數重命名指定文件。
rename() 原型
int rename( const char *oldname, const char *newname );
rename()
函數接受兩個參數:oldname
, newname
並返回一個整數值。它將 oldname 指向的字符串表示的文件重命名為 newname
指向的字符串。
它在<cstdio> 頭文件中定義。
參數:
oldname
:指向包含文件舊名稱以及要重命名的路徑的字符串的指針。newname
:指向包含文件新名稱和路徑的字符串的指針。
返回:
rename() 函數返回:
- 如果文件重命名成功,則為零。
- 如果發生錯誤,則非零。
示例 1:rename() 函數的工作原理
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char oldname[] = "file_old.txt";
char newname[] = "file_new.txt";
/* Deletes the file if exists */
if (rename(oldname, newname) != 0)
perror("Error renaming file");
else
cout << "File renamed successfully";
return 0;
}
運行程序時,輸出將是:
- 如果文件重命名成功:
File renamed successfully
- 如果文件不存在:
Error renaming file: No such file or directory
rename()
函數還可用於將文件移動到其他位置。這可以通過為文件的新名稱提供不同的路徑來完成。
示例 2:rename() 函數移動文件
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char oldname[] = "C:\\Users\\file_old.txt";
char newname[] = "C:\\Users\\New Folder\\file_new.txt";
/* Deletes the file if exists */
if (rename(oldname, newname) != 0)
perror("Error moving file");
else
cout << "File moved successfully";
return 0;
}
運行程序時,輸出將是:
- 如果文件移動成功:
File moved successfully
- 如果文件不存在:
Error moving file: No such file or directory
相關用法
- C++ rename用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ remainder()用法及代碼示例
- C++ remquo()用法及代碼示例
- C++ rewind()用法及代碼示例
- C++ remove()用法及代碼示例
- C++ realloc()用法及代碼示例
- C++ real()用法及代碼示例
- C++ rint(), rintf(), rintl()用法及代碼示例
- C++ rotate用法及代碼示例
- C++ ratio_less_equal()用法及代碼示例
- C++ rint()用法及代碼示例
- C++ ratio_less()用法及代碼示例
- C++ round()用法及代碼示例
- C++ raise()用法及代碼示例
- C++ ratio_greater()用法及代碼示例
- C++ ratio_not_equal()用法及代碼示例
- C++ ratio_greater_equal()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ unordered_map cbegin用法及代碼示例
注:本文由純淨天空篩選整理自 C++ rename()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。