歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> UNIX系統編程小結(二)------文件和目錄

UNIX系統編程小結(二)------文件和目錄

日期:2017/3/1 10:05:50   编辑:Linux編程

一.對linux的安全機制的一點感悟

各種權限,read,write,execute,set-user-ID,set-group-ID,sticky bit,對目錄的權限,對文件的權限,用於保證系統安全的各種組合技,各種經典。比如,如果我們想unlink一個文件,就必須擁有該文件所在目錄的write與execute的權限。

二.兩個小例子

1.當文件有hole時,cp命令會同時拷貝這些hole為'\0'。這裡是一個實現了拷貝時跳過文件hole的程序。ps:我用的buffer是一個字節的,效率很低,但如果用大的buffer就會使得hole被移除,使得原先分開的字符被連上。我沒想好如何解決這個問題。如果您知道,請您告訴小弟我,非常感謝!

相關閱讀:

UNIX系統編程小結(一)------文件I/O http://www.linuxidc.com/Linux/2012-12/75688.htm

Unix/Linux編程實踐教程【高清PDF中文版+附錄光盤+代碼】:http://www.linuxidc.com/Linux/2011-08/41374.htm

#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將該目錄設置為當前的工作目錄,可以提高程序運行的效率。

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;
}

Copyright © Linux教程網 All Rights Reserved