要完成一个目录的广度优先的遍历,显示每一个普通文件的最后修改时间,自己用的是建立链表将文件夹路径插入链表然后只要判断链表不空就打开的方式,但是不知道哪里有错 实在是找不到问题,求帮助!
直接把源代码也贴上来了
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
struct node{
char date[100];
struct node* next;
};
static int get_file_size_time(const char *filename){
struct stat statbuf;
if(stat(filename,&statbuf)==-1){
printf("get stat on %s erro:%s\n",filename,strerror(errno));
return(-1);
}
if(S_ISDIR(statbuf.st_mode))
return(1); //是目录文件
if(S_ISREG(statbuf.st_mode))
printf("%s \tsize:%ldbytes\tmodifiedat%s",filename,statbuf.st_size,ctime(&statbuf.st_mtime)); //修改文件大小和最后修改时间
return(0);
}
struct node init(char *filename){
struct node *head,
head=(node)malloc(sizeof(node));
head->date=filename;
head->next=NULL;
return(head);
}
void insert(node end,char *path){
struct node *s;
s=(node)malloc(sizeof(node));
s->date=path;
s->next=NULL;
end->next=s;
}
struct node *getend(node *head){
while(head->next!=NULL){
head=head->next;
}
return(head);
}
int main(int argc,char **argv){
struct node *head;
struct node *end;
DIR *dirp;
struct dirent *direntp;
char path[1024];
if(argc!=2){ //判断输入是否为俩个参数
printf("Usage: %s filename\n\a",argv[0]);
exit(1);
}
head=init(argv[1]);
while(head!=NULL){
if((dirp=opendir(head->date))==NULL){
printf("open directory %s erro%s\n",head->date,strerror(errno));
exit(1);
}
while((direntp=readdir(dirp))!=NULL){
if(!strcmp(direntp->d_name,"source.txt")){
printf("we have find the file source!\n");
int fdr,fdw,len;
char str[1024];
fdr=open("source.txt",O_RDONLY);
if(fdr)
len=read(fdr,str,1024);
else{
printf("read file error");
exit(0);
}
fdw=open("target.txt",O_CREAT|O_RDWR|S_IXUSR);
write(fdw,str,len);
lose(fdr);
close(fdw);
}
memset(path,0,1024);
strcpy(path,head->date);
strcat(path,"/");
strcat(path,direntp->d_name);
if(get_file_size_time(path)==1){
end=getend(head);
insert(end,path);
}
if(get_file_size_time(path)==-1)
break;
}
head=head->next;
}
closedir(dirp);
exit(1);
}
head->date=filename; 这样不行,前面是数组,后面是指针,要拷贝才行。