首页 新闻 会员 周边

linux下一段c程序open打开文件问题

0
悬赏园豆:5 [已关闭问题] 关闭于 2014-03-18 14:45
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct filelist{ char *name; long int lenth; }file_list; file_list* scanfile(char *dirname){ struct dirent **namelist; struct stat buf; int n; n= scandir(dirname,&namelist,0,alphasort); //扫描目录下的文件 if(n<0) perror("error occurred!"); file_list *flist; flist = (file_list *)malloc(n*sizeof(file_list)); int filecount = 0; int i; for(i=0; i < n; i++){ if(strcmp(namelist[i]->d_name,".") != 0&&strcmp(namelist[i]->d_name,"..") != 0){ flist[filecount].name = (char *)malloc(128); //flist[filecount].name= strdup(dirname); strcpy(flist[filecount].name, dirname); strcat(flist[filecount].name,namelist[i]->d_name); printf("file name: %s \n",flist[filecount].name); int fildes = open(flist[filecount].name,O_RDONLY); //打开文件 // stat(flist[filecount].name,&buf); flist[filecount].lenth = (int)lseek(fildes,0,SEEK_END); //获取文件长度 //flist[filecount].lenth=buf.st_size; printf("file lenth : %s \n",flist[filecount].lenth); close(fildes); filecount++; //文件计数+1 } printf("file count: %d \n",filecount); }
return flist }
int main(int argc, char **argv){ file_list *flst; // if( argc != 2 ){ // printf("usage : %s dirname \n", argv[0]); // exit(-1); // } // else flst=scanfile("/home/test"); return 0; }

上面这段代码视为了扫描一个目录下所有文件,并把文件指针和大小存储到自定义的结构filelist中。运行出现段错误  

gdb调试错误是

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a5ef90 in _IO_vfprintf_internal (s=<optimized out>,
format=<optimized out>, ap=ap@entry=0x7fffffffda18) at vfprintf.c:1655
1655 vfprintf.c: 没有那个文件或目录.

似乎是open打开文件处出现问题了,但又无法确定 求解到底是哪个位置出问题了

open打开文件返回-1 ,无法正确得到文件长度 感觉是没有正确得到文件路径 但打印出来的路径又是正确的,求解答

espace的主页 espace | 菜鸟二级 | 园豆:202
提问于:2014-03-17 19:36
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册