文件的移动,删除 rename remove unlink 函数
2017-01-22 14:02
405 查看
int rename(const char *oldpath, const char *newpath);
rename() renames a file, moving it between directories if required.
利用rename实现简单的mv指令
文件的删除可以使用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,但是有进程打开了这个文件,则文件暂不删除,直到打开文件的所有进程都结束时,文件才被删除,利用这点可以确保
即使程序崩溃,它所创建的临时文件也不会遗留下来。
例:
最后mm文件被删除了。
程序在创建并打开了文件mm之后,调用了unlink,之后再对文件进行读写操作。
程序如果在unlink之后的代码中出现崩溃,则在程序结束时,temp文件也不会遗留下来。
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文件也不会遗留下来。
相关文章推荐
- 文件的移动删除rename/remove
- C语言rename()函数和remove()函数:重命名文件或目录、删除文件或目录
- Shell的文件操作函数SHFileOperation 移动,复制,删除文件
- 文件磁盘相关函数[8]-删除文件夹 RemoveDir; RemoveDirectory
- 移动文件、修改文件名函数rename
- PHP unlink()函数,删除文件
- PHP操作文件类的函数代码(文件和文件夹创建,复制,移动和删除)
- Linux中对文件删除函数unlink的操作
- C语言unlink()函数:删除文件
- SHFileOperation()的外壳函数,用它可以实现各种文件操作,如文件的拷贝、删除、移动等
- C语言remove()函数:删除文件或目录
- Linux中对文件删除函数unlink的操作
- PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
- 文件与目录操作--link、unlink、remove和rename函数 及 文件与目录--utime函数
- php的unlink()函数删除上级目录文件
- shellapi的SHFileOperation()的外壳函数,用它可以实现各种文件操作,如文件的拷贝、删除、移动等
- 使用remove()函数删除文件
- C 语言删除文件函数 remove()
- SHFileOperation()函数移动,复制,删除文件\文件夹
- C语言判断文件夹或者文件是否存在以及权限等信息access函数和删除文件或目录 remove()函数使用实例