我必须像用 C 语言一样编写一个 ls,但我有一些问题。使用 opendir 打开目录后,如果我不使用 printf 或 puts 打印路径名,则在 closedir 执行时会出现核心转储错误,但如果我确实打印路径,代码工作正常。
const char * cwd=".";
DIR * dir=opendir(cwd);
//that print --> printf("%s",cwd);
if(dir==NULL){
puts("ohlala");
}
char * filename;
struct dirent * truc;
struct stat * filestat=malloc(sizeof(struct stat *));
while((truc=readdir(dir))!=NULL){
filename=truc->d_name;
if(strcmp(filename,"..")!=0 && strcmp(filename,".")!=0){
if(l==0){
printf("%-s ",filename);
}else if(l==1){
if(stat(filename,filestat)!=0){
printf("Erreur stat de %sn",filename);
exit(1);
}
printf("%ld %-s ",filestat->st_ino,filename);
}
}
}
//gdb is telling me the probleme is here
closedir(dir);
return 0;
有什么想法吗?谢谢。
您没有正确分配filestat
:此行
struct stat * filestat = malloc(sizeof(struct stat *))
应该是
struct stat * filestat = malloc(sizeof(struct stat))
没有星号。目前,对 stat
的调用会写入分配的内存块,从而导致未定义的行为。
请注意,您不需要动态分配filestat
:使其成为局部变量,并将&filestat
传递给stat
调用:
struct stat filestat;
...
if(stat(filename, &filestat) != 0) {
...
}
...
printf("%ld %-s ", filestat.st_ino, filename);