重新命名 C/C++ 函式


C 庫函式 int rename(const char *old_filename, const char *new_filename) 會將由 old_filename 引用檔名更改為 new_filename

以下是 rename() 函式的宣告。

int rename(const char *old_filename, const char *new_filename)

引數 old_filename − 這是包含要重新命名和/或移動的檔名的 C 字串,new_filename − 這是包含檔案新名稱的 C 字串。

成功時,會返回零。如果出錯,則返回 -1,且 errno 會被適當地設定。

示例

#include <stdio.h>
int main () {
   int ret;
   char oldname[] = "file.txt";
   char newname[] = "newfile.txt";
   ret = rename(oldname, newname);
   if(ret == 0) {
      printf("File renamed successfully");
   } else {
      printf("Error: unable to rename the file");
   }
   return(0);
}

我們假設有一個文字檔案 file.txt,其中有一些內容。因此,我們將使用上述程式重新命名此檔案。我們編譯並執行上述程式,生成以下訊息,並且該檔案將重新命名為 newfile.txt 檔案。

輸出

File renamed successfully

更新時間:2019 年 7 月 30 日

303 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.