- 论坛徽章:
- 0
|
各位好:
在redhat5上实现一个程序,将一个文件夹完整的拷贝到另一个地方,目前实现了文件夹文件的类型判断,请问如何读写文件夹?难道一定要使用mkdir创建吗?按照apue的说法,文件夹也是一个文件,如何读写,我试过用fread和read都不能读。
下面的代码,作用是遍历文件夹,统计普通文件和文件夹的项数,请指教。
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
int Mydir(char *filepath);
int main(int argc, char *argv[])
{
char *path;
if(argc!=2)
return 1;
path=argv[1];
Mydir(path);
return 0;
}
int Mydir(char *filepath)
{
char *fullpath,*filetype,*tmp;
struct stat statbuf;
DIR *dr;
struct dirent *drt;
if((dr=opendir(filepath))==NULL)
return 2;
while((drt=readdir(dr))!=NULL)
{
if(strcmp(drt->d_name,".")==0||strcmp(drt->d_name,"..")==0)
continue;
fullpath=strdup(filepath);
fullpath=strcat(fullpath,"/");
fullpath=strcat(fullpath,drt->d_name);
if(stat(fullpath,&statbuf)<0)
return 3;
if (S_ISREG(statbuf.st_mode))
{
filetype="reguler";
printf("%s,%s\n",fullpath,filetype);
}
else if(S_ISDIR(statbuf.st_mode))
{
filetype="directory";
//fullpath=strcat(fullpath,"/");
printf("%s,%s\n",fullpath,filetype);
tmp=strdup(fullpath);
Mydir(tmp);
}
else
{
filetype="invalid";
printf("%s,%s\n",fullpath,filetype);
}
//printf("%s,%s\n",fullpath,filetype);
bzero(fullpath,strlen(fullpath));
}
return 0;
} |
|