unix——文件和目录
1.当文件有hole时,cp命令会同时拷贝这些hole为'\0'。这里是一个实现了拷贝时跳过文件hole的程序。ps:我用的buffer是一个字节的,效率很低,但如果用大的buffer就会使得hole被移除,使得原先分开的字符被连上。我没想好如何解决这个问题。如果您知道,请您告诉小弟我,非常感谢!
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include <apue.h> #include <my_error.h> #include <fcntl.h> int main() { char buf[1]; int fd,fd_to; int n; if( (fd=open("temp_in_hole",O_RDWR) )<0) err_sys("error open"); if( (fd_to=open("temp_OUT_hole",O_WRONLY))<0 ) err_sys("error open for "); while( (n=read(fd,buf,1))!=0 ) { if(buf[0]!='\0') if(write(fd_to,buf,1)!=n) err_sys("error write"); } close(fd); close(fd_to); return 0; }
2.遍历目录。这里只贴出主要代码: ps:有一个技巧就是每遇到一个目录时,就用chdir将该目录设置为当前的工作目录,可以提高程序运行的效率。
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
static int dopath(Myfunc * func) { struct stat statbuf; struct dirent *dirp; DIR *dp; int ret; char *ptr; if(lstat(fullpath,&statbuf)<0) return (func(fullpath,&statbuf,FTW_NS)); if(S_ISDIR(statbuf.st_mode)==0) return (func(fullpath,&statbuf,FTW_F)); if( (ret=func(fullpath,&statbuf,FTW_D))!=0 ) return ret; ptr=fullpath+strlen(fullpath); *ptr++='/'; *ptr=0; if(chdir(fullpath)<0) err_ret("chdir for %s failed!",fullpath); if((dp=opendir("./"))==NULL) return (func(fullpath,&statbuf,FTW_DNR)); while((dirp=readdir(dp))!=NULL) { if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0) continue; strcpy(ptr,dirp->d_name); if(ret=dopath(func)!=0) return ret; } ptr[-1]=0; if(closedir(dp)<0) err_ret("can't close directory %s",fullpath); if(chdir("../")<0) err_ret("chdir for ../ failed!"); return ret; }