------------------------------文件�}�u
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#define MAX_PATH 1024
void copy_file(char *src,char *dest);
void dirwalk(char *dir,void (*fcn)(char *,char *),char *destname);
void dirwalk(char *dir,void (*fcn)(char *,char *),char *destname)
{
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if((dfd=opendir(dir))==NULL){
fprintf(stderr,"dirwalk:can't open %s\n",dir);
return;
}
while((dp=readdir(dfd))!=NULL){
if(strcmp(dp->d_name,".")==0||strcmp(dp->d_name,"..")==0) continue;
sprintf(name,"%s/%s",dir,dp->d_name);
(*fcn)(name,destname);
}
closedir(dfd);
}
void fsize(char *srcname,char *destname)
{
struct stat stbuf;
char filename[1024]={0};
if(lstat(srcname,&stbuf)==-1){
fprintf(stderr,"fsize:can't access %s\n",srcname);
return;
}
char *pos=strrchr(srcname,'/');
if(pos)
sprintf(filename,"%s%s",destname,pos);
else
sprintf(filename,"%s/%s",destname,srcname);
if((stbuf.st_mode&S_IFMT)==S_IFDIR){
mkdir(filename,0755);
dirwalk(srcname,fsize,filename);
}
else{
printf("%s %s\n",srcname,filename);
copy_file(srcname,filename);
}
}
void copy_file(char *src,char *dest)
{
int fr,fw,len;
char buf[10]={0};
fr=open(src,O_RDONLY);
if(fr<0){
perror("open error");
exit(1);
}
fw=open(dest,O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fw<0){
perror("open error");
exit(1);
}
while((len=read(fr,buf,10))>0)
{
write(fw,buf,len);
}
close(fr);
close(fw);
}
int main(int argc,char *argv[])
{
if(argc==3)
{
dirwalk(argv[1],fsize,argv[2]); //copy without root
//fsize(argv[1],argv[2]); //copy with root
}
else
{
printf("you need input two pars\n");
exit(1);
}
return 0;
}
------------------------------文件查找
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PATH 1024
void dirwalk(char *dir,void (*fcn)(char *))
{
char name[MAX_PATH];
struct dirent *dp;
DIR *dfd;
if((dfd=opendir(dir))==NULL){
fprintf(stderr,"dirwalk:can't open %s\n",dir);
return;
}
while((dp=readdir(dfd))!=NULL){
if(strcmp(dp->d_name,".")==0||strcmp(dp->d_name,"..")==0)
continue;
if(strlen(dir)+strlen(dp->d_name)+2>sizeof(name))
fprintf(stderr,"dirwalk:name %s %s too long\n",dir,dp->d_name);
else{
sprintf(name,"%s/%s",dir,dp->d_name);
(*fcn)(name);
}
}
closedir(dfd);
}
void fsize(char *name)
{
struct stat stbuf;
if(lstat(name,&stbuf)==-1){
fprintf(stderr,"fsize:can't access %s\n",name);
return;
}
if((stbuf.st_mode&S_IFMT)==S_IFDIR)
dirwalk(name,fsize);
printf("%8ld %s\n",stbuf.st_size,name);
}
int main(int argc,char *argv[])
{
if(argc==1)
fsize(".");
else
while(--argc>0)
fsize(*++argv);
return 0;
}