21. rename - 重命名文件或目錄
函數介紹
rename
系統調用用于重命名文件或目錄,也可以將文件或目錄移動到另一個位置。如果目標文件已存在,則會被替換。
函數原型
#include <stdio.h>int rename(const char *oldpath, const char *newpath);
功能
將文件或目錄從舊路徑重命名為新路徑。
參數
const char *oldpath
: 原文件或目錄的路徑名const char *newpath
: 新文件或目錄的路徑名
返回值
- 成功時返回0
- 失敗時返回-1,并設置errno:
EACCES
: 權限不足EBUSY
: 文件正被使用EDQUOT
: 磁盤配額超限EEXIST
: 目標文件存在且不能被替換EINVAL
: 參數無效EISDIR
: newpath是目錄但oldpath是文件ELOOP
: 符號鏈接循環EMLINK
: 鏈接數超限ENAMETOOLONG
: 路徑名過長ENOENT
: 原文件不存在或目標目錄不存在ENOSPC
: 磁盤空間不足ENOTDIR
: 路徑前綴不是目錄ENOTEMPTY
: 目標目錄非空EPERM
: 操作不被允許EROFS
: 文件系統只讀EXDEV
: 跨文件系統移動
相似函數
renameat()
: 相對路徑版本renameat2()
: 增強版本,支持更多選項
示例代碼
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <limits.h>int main() {char buffer[PATH_MAX];char original_dir[PATH_MAX];printf("=== Rename函數示例 ===\n");// 保存原始目錄if (getcwd(original_dir, sizeof(original_dir)) == NULL) {perror("獲取原始目錄失敗");exit(EXIT_FAILURE);}// 示例1: 基本的文件重命名操作printf("\n示例1: 基本的文件重命名操作\n");// 創建測試文件const char *old_filename = "test_rename_old.txt";int fd = open(old_filename, O_CREAT | O_WRONLY, 0644);if (fd == -1) {perror("創建測試文件失敗");exit(EXIT_FAILURE);}const char *file_content = "This is test content for rename function demonstration.";if (write(fd, file_content, strlen(file_content)) == -1) {perror("寫入文件內容失敗");}close(fd);printf("創建測試文件: %s\n", old_filename);// 重命名文件const char *new_filename = "test_rename_new.txt";if (rename(old_filename, new_filename) == -1) {perror("重命名文件失敗");} else {printf("成功將 %s 重命名為 %s\n", old_filename, new_filename);// 驗證文件是否存在if (access(new_filename, F_OK) == 0) {printf("新文件存在\n");// 讀取文件內容驗證fd = open(new_filename, O_RDONLY);if (fd != -1) {char read_buffer[200];ssize_t bytes_read = read(fd, read_buffer, sizeof(read_buffer) - 1);if (bytes_read > 0) {read_buffer[bytes_read] = '\0';printf("文件內容: %s\n", read_buffer);}close(fd);}}if (access(old_filename, F_OK) != 0) {printf("原文件已不存在\n");}}// 示例2: 目錄重命名操作printf("\n示例2: 目錄重命名操作\n");// 創建測試目錄const char *old_dirname = "test_rename_old_dir";const char *new_dirname = "test_rename_new_dir";if (mkdir(old_dirname, 0755) == -1 && errno != EEXIST) {perror("創建測試目錄失敗");} else {printf("創建測試目錄: %s\n", old_dirname);// 在目錄中創建文件char file_in_dir[PATH_MAX];snprintf(file_in_dir, sizeof(file_in_dir), "%s/content.txt", old_dirname);fd = open(file_in_dir, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *dir_content = "Content in directory file";write(fd, dir_content, strlen(dir_content));close(fd);printf("在目錄中創建文件: content.txt\n");}// 重命名目錄if (rename(old_dirname, new_dirname) == -1) {perror("重命名目錄失敗");} else {printf("成功將目錄 %s 重命名為 %s\n", old_dirname, new_dirname);// 驗證目錄和內容if (access(new_dirname, F_OK) == 0) {printf("新目錄存在\n");// 檢查目錄中的文件char new_file_path[PATH_MAX];snprintf(new_file_path, sizeof(new_file_path), "%s/content.txt", new_dirname);if (access(new_file_path, F_OK) == 0) {printf("目錄中的文件也已移動\n");}}if (access(old_dirname, F_OK) != 0) {printf("原目錄已不存在\n");}}}// 示例3: 文件移動操作printf("\n示例3: 文件移動操作\n");// 創建另一個目錄用于移動測試const char *move_to_dir = "move_destination";if (mkdir(move_to_dir, 0755) == -1 && errno != EEXIST) {perror("創建目標目錄失敗");} else {printf("創建目標目錄: %s\n", move_to_dir);// 創建要移動的文件const char *file_to_move = "file_to_move.txt";fd = open(file_to_move, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *move_content = "This file will be moved to another directory";write(fd, move_content, strlen(move_content));close(fd);printf("創建要移動的文件: %s\n", file_to_move);}// 移動文件到另一個目錄char destination_path[PATH_MAX];snprintf(destination_path, sizeof(destination_path), "%s/%s", move_to_dir, file_to_move);if (rename(file_to_move, destination_path) == -1) {perror("移動文件失敗");} else {printf("成功將文件 %s 移動到 %s\n", file_to_move, destination_path);// 驗證移動結果if (access(destination_path, F_OK) == 0) {printf("文件已在目標位置\n");}if (access(file_to_move, F_OK) != 0) {printf("原位置文件已不存在\n");}}}// 示例4: 替換已存在文件printf("\n示例4: 替換已存在文件\n");// 創建目標文件const char *target_file = "target_file.txt";fd = open(target_file, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *target_content = "Original content that will be replaced";write(fd, target_content, strlen(target_content));close(fd);printf("創建目標文件: %s\n", target_file);}// 創建源文件const char *source_file = "source_file.txt";fd = open(source_file, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *source_content = "New content that will replace the old content";write(fd, source_content, strlen(source_content));close(fd);printf("創建源文件: %s\n", source_file);}// 讀取替換前的目標文件內容printf("替換前目標文件內容:\n");fd = open(target_file, O_RDONLY);if (fd != -1) {char content_buffer[200];ssize_t bytes_read = read(fd, content_buffer, sizeof(content_buffer) - 1);if (bytes_read > 0) {content_buffer[bytes_read] = '\0';printf(" %s\n", content_buffer);}close(fd);}// 使用rename替換文件if (rename(source_file, target_file) == -1) {perror("替換文件失敗");} else {printf("成功使用 %s 替換 %s\n", source_file, target_file);// 驗證替換結果printf("替換后目標文件內容:\n");fd = open(target_file, O_RDONLY);if (fd != -1) {char content_buffer[200];ssize_t bytes_read = read(fd, content_buffer, sizeof(content_buffer) - 1);if (bytes_read > 0) {content_buffer[bytes_read] = '\0';printf(" %s\n", content_buffer);}close(fd);}// 源文件應該不存在了if (access(source_file, F_OK) != 0) {printf("源文件已被移除\n");}}// 示例5: 錯誤處理演示printf("\n示例5: 錯誤處理演示\n");// 嘗試重命名不存在的文件if (rename("nonexistent_file.txt", "new_name.txt") == -1) {printf("重命名不存在的文件: %s\n", strerror(errno));}// 嘗試重命名到只讀文件系統if (rename(target_file, "/proc/test") == -1) {printf("重命名到只讀文件系統: %s\n", strerror(errno));}// 嘗試使用過長的路徑名char long_path[PATH_MAX + 100];memset(long_path, 'a', sizeof(long_path) - 1);long_path[sizeof(long_path) - 1] = '\0';if (rename(target_file, long_path) == -1) {printf("使用過長路徑名: %s\n", strerror(errno));}// 示例6: 實際應用場景printf("\n示例6: 實際應用場景\n");// 場景1: 日志文件輪轉printf("場景1: 日志文件輪轉\n");const char *log_file = "application.log";const char *old_log_file = "application.log.1";// 創建日志文件fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0644);if (fd != -1) {for (int i = 0; i < 10; i++) {char log_entry[100];sprintf(log_entry, "Log entry %d: Application running normally\n", i);write(fd, log_entry, strlen(log_entry));}close(fd);printf("創建日志文件并寫入測試數據\n");}// 模擬日志輪轉if (access(old_log_file, F_OK) == 0) {unlink(old_log_file); // 刪除舊的備份}if (rename(log_file, old_log_file) == -1) {perror("日志輪轉失敗");} else {printf("日志文件輪轉成功: %s -> %s\n", log_file, old_log_file);// 創建新的日志文件fd = open(log_file, O_CREAT | O_WRONLY | O_APPEND, 0644);if (fd != -1) {const char *new_log_msg = "New log file created after rotation\n";write(fd, new_log_msg, strlen(new_log_msg));close(fd);printf("創建新的日志文件\n");}}// 場景2: 臨時文件處理printf("場景2: 臨時文件處理\n");const char *temp_file = "temp_processing.tmp";const char *final_file = "final_result.txt";// 創建臨時文件fd = open(temp_file, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *temp_content = "Processing result data that needs to be finalized";write(fd, temp_content, strlen(temp_content));close(fd);printf("創建臨時處理文件: %s\n", temp_file);}// 處理完成后重命名為最終文件if (rename(temp_file, final_file) == -1) {perror("重命名臨時文件失敗");} else {printf("臨時文件處理完成: %s -> %s\n", temp_file, final_file);}// 場景3: 原子性文件更新printf("場景3: 原子性文件更新\n");const char *config_file = "config.txt";const char *temp_config = "config.txt.tmp";// 創建原始配置文件fd = open(config_file, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *old_config = "old_parameter=value1\nold_setting=enabled\n";write(fd, old_config, strlen(old_config));close(fd);printf("創建原始配置文件\n");}// 創建新的配置文件(臨時)fd = open(temp_config, O_CREAT | O_WRONLY, 0644);if (fd != -1) {const char *new_config = "new_parameter=value2\nnew_setting=disabled\nupdated=true\n";write(fd, new_config, strlen(new_config));close(fd);printf("創建新配置文件(臨時)\n");}// 原子性地替換配置文件if (rename(temp_config, config_file) == -1) {perror("原子性替換配置文件失敗");} else {printf("原子性更新配置文件成功\n");// 驗證新配置printf("更新后的配置文件內容:\n");fd = open(config_file, O_RDONLY);if (fd != -1) {char config_buffer[300];ssize_t bytes_read = read(fd, config_buffer, sizeof(config_buffer) - 1);if (bytes_read > 0) {config_buffer[bytes_read] = '\0';printf("%s", config_buffer);}close(fd);}}// 示例7: 跨文件系統操作限制printf("\n示例7: 跨文件系統操作限制\n");// 這個測試需要實際的跨文件系統環境printf("說明: rename不能跨文件系統移動文件\n");printf("如果嘗試這樣做,會返回EXDEV錯誤\n");printf("跨文件系統移動需要先復制再刪除原文件\n");// 示例8: 性能考慮printf("\n示例8: 性能考慮\n");// rename操作通常是原子性的且很快printf("rename操作的特點:\n");printf(" - 原子性: 操作要么完全成功,要么完全失敗\n");printf(" - 高效性: 通常只是修改元數據,不移動實際數據\n");printf(" - 限制性: 不能跨文件系統操作\n");// 清理測試資源printf("\n清理測試資源...\n");// 刪除各種測試文件和目錄const char *files_to_delete[] = {"test_rename_new.txt","target_file.txt","source_file.txt","file_to_move.txt","application.log","application.log.1","final_result.txt","config.txt"};for (int i = 0; i < 8; i++) {if (access(files_to_delete[i], F_OK) == 0) {if (unlink(files_to_delete[i]) == -1) {printf("刪除文件 %s 失敗: %s\n", files_to_delete[i], strerror(errno));} else {printf("刪除文件: %s\n", files_to_delete[i]);}}}// 刪除目錄if (access("test_rename_new_dir", F_OK) == 0) {char dir_file[PATH_MAX];snprintf(dir_file, sizeof(dir_file), "%s/content.txt", "test_rename_new_dir");unlink(dir_file);if (rmdir("test_rename_new_dir") == -1) {printf("刪除目錄失敗: %s\n", strerror(errno));} else {printf("刪除目錄: test_rename_new_dir\n");}}if (access(move_to_dir, F_OK) == 0) {char moved_file[PATH_MAX];snprintf(moved_file, sizeof(moved_file), "%s/file_to_move.txt", move_to_dir);unlink(moved_file);if (rmdir(move_to_dir) == -1) {printf("刪除目標目錄失敗: %s\n", strerror(errno));} else {printf("刪除目錄: %s\n", move_to_dir);}}return 0;
}