mv 改名的功能内部调用 rename, 而rename 内部又调用了 link 和 unlink,
模拟片段:
- int link_based_rename(char *oldname, char *newname)
- {
- if ( link(oldname, newname) != -1 )
- {
- if ( unlink(oldname) == -1 ){
- unlink(newname); //删除old不成功,那么还保留old, 删除掉新的。。可是删除新的也不成共咋办??
- return -1;
- }
- return 0;
- }
- return -1;
- }
另外, rename不能跨文件系统操作,所以如果要用rename来重命名文件,需要如下代码:
- main()
- {
- rv = rename(src,destfilename);
- /*
- * If target is different file system, try copy and remove
- */
- if ( rv == -1 && errno == EXDEV ) //in errno.h #define EXDEV 18 /* Cross-device link */
- rv = copy_and_unlink(src,destfilename);
- }
- copy_and_unlink(char *old, char *new)
- {
- FILE *fpin, *fpout;
- int c;
- int rv = 0;
- /** open files **/
- if ( (fpin = fopen(old,"r")) == NULL )
- return -1;
- if ( (fpout = fopen(new, "w")) == NULL ){
- fclose(fpin);
- return -1;
- }
- /** do copy **/
- while( rv == 0 && (c = getc(fpin)) != EOF )
- if ( putc(c, fpout) == EOF )
- rv = -1;
- /** close files: if error, abandon project **/
- if ( fclose(fpin) == EOF || fclose(fpout) == EOF ){
- rv = -1;
- unlink(new);
- }
- /** otherwise try to unlink original **/
- else if ( unlink(old) == -1 ){
- rv = -1;
- unlink(new);
- }
- /** **/
- return rv;
- }
阅读(2041) | 评论(0) | 转发(1) |