int rename(const char *oldpath, const char *newpath);
rename() renames a file, moving it between directories if required.
利用rename實現簡單的mv指令
#include <stdio.h> #include <stdlib.h> #include <errno.h> int main(int argc, char* argv[]) { if (argc !=3) { printf("need old an new file\n"); exit(0); } if (-1 == rename(argv[1], argv[2])) { perror("rename"); exit(0); } return 0; }
文件的刪除可以使用unlink系統調用。目錄的刪除可以使用rmdir系統調用。而通用的既能刪除文件又能刪除目錄的系統調用是remove
remove系統調用實際上是在內部封裝了unlink和rmdir,當需要刪除文件時調用unlink,當需要刪除目錄時調用rmdir
int unlink(const char *pathname);
If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.
If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.
如果文件的鏈接數為0,但是有進程打開了這個文件,則文件暫不刪除,直到打開文件的所有進程都結束時,文件才被刪除,利用這點可以確保
即使程序崩潰,它所創建的臨時文件也不會遺留下來。
例:
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> int main(int argc, char* argv[]) { int fd; char buf[30]; fd = open("mm", O_CREAT|O_RDWR, S_IRWXU); unlink("mm"); write(fd, "temp", 5); lseek(fd, 0, SEEK_SET); read(fd, buf, 5); printf("read %s\n", buf); return 0; }
最后mm文件被刪除了。
程序在創建並打開了文件mm之后,調用了unlink,之后再對文件進行讀寫操作。
程序如果在unlink之后的代碼中出現崩潰,則在程序結束時,temp文件也不會遺留下來。