c - 遍历目录并打印一些信息
问题描述
我想编写一个 C 程序,它将文件夹的路径作为参数,并显示有关它包含的文件的一些信息。
到目前为止,我已经写了这个:
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv){
char* dir_path = argv[1];
char* dir_path_bar = strcat(dir_path, "/");
DIR* dir = opendir(dir_path);
for(struct dirent* entry = readdir(dir); entry != NULL; entry = readdir(dir)){
printf("Next entry is %s\n", entry->d_name);
char* entry_path = strcat(dir_path_bar, entry->d_name);
printf("%s\n", entry_path);
struct stat buf;
stat(entry_path, &buf);
printf("Its inode number is %s\n", entry->d_ino);
printf("Its inode number is %s\n", buf.st_ino);
printf("Its uid is %s\n", buf.st_uid);
printf("Its size is %s bytes\n", buf.st_size);
};
closedir(dir);
}
哪个stat
可以编译,但是这个电话给了我一个 SEGFAULT。到底是怎么回事?
解决方案
正如其他人所提到的,您不能附加到argv[1]
. 您不能继续在循环内附加它。而且,你不能%s
用来输出数字。
这是带有注释和修复的错误的代码[#if 0
用于显示旧代码]:
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
char *dir_path = argv[1];
// NOTE/BUG: argv[1] has a fixed size you can't append to it
#if 0
char *dir_path_bar = strcat(dir_path, "/");
#else
char dir_path_bar[PATH_MAX];
strcpy(dir_path_bar,dir_path);
strcat(dir_path_bar,"/");
#endif
DIR *dir = opendir(dir_path);
#if 1
if (dir == NULL) {
perror(dir_path);
exit(1);
}
#endif
for (struct dirent *entry = readdir(dir); entry != NULL;
entry = readdir(dir)) {
printf("Next entry is %s\n", entry->d_name);
// NOTE/BUG: because you don't reset dir_path_bar, this just keeps appending
// to it
#if 0
char *entry_path = strcat(dir_path_bar, entry->d_name);
#else
char entry_path[PATH_MAX];
strcpy(entry_path,dir_path_bar);
strcat(entry_path,entry->d_name);
#endif
printf("\n");
printf("%s\n", entry_path);
struct stat buf;
stat(entry_path, &buf);
// NOTE/BUG: these need one or more of: %d/%ld/%lld (vs %s)
#if 0
printf("Its inode number is %s\n", entry->d_ino);
printf("Its inode number is %s\n", buf.st_ino);
printf("Its uid is %s\n", buf.st_uid);
printf("Its size is %s bytes\n", buf.st_size);
#else
printf("Its inode number is %ld\n", entry->d_ino);
printf("Its inode number is %ld\n", buf.st_ino);
printf("Its uid is %d\n", buf.st_uid);
printf("Its size is %ld bytes\n", buf.st_size);
#endif
};
closedir(dir);
return 0;
}
推荐阅读
- php - Apache 将 PHP 数组标记作为结束标记处理
- android - 以编程方式在 ActionBar 上设置 app:contentInsetStartWithNavigation
- c# - 从身份中删除引导程序
- python - 从嵌套子列表返回八元组模式
- java - 那个json有什么相同的属性?
- c# - 删除字符串中第四个空格之后的所有字符
- ruby-on-rails - 在 Ruby on Rails 中调用控制器函数时,如何保留相同的浏览器视图/页面?
- r - r - 地图与复杂布局中的绘图边界重叠
- java - 使用 Java 在 Android 中将接收意图设置回默认值
- function - 在 Golang 中使用类型别名声明函数