gpt4 book ai didi

c - 获取文件详细信息时出现错误结果 C

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:00 24 4
gpt4 key购买 nike

我有以下函数抽象了 C 中 stat 结构的处理

int isdir(const char *filename) {
struct stat st_buf;
stat(filename, &st_buf);
if(S_ISDIR(st_buf.st_mode))
return 0;
return 1;
}

主函数调用isdir

int main(...) {
struct dirent *file;
DIR *dir = opendir(argv[1]);

while(file = readdir(dir)) {
printf("%d\n", isdir(file->d_name));
}
closedir(dir);
/* other code */
}

我有一个名为 Test 的文件夹作为程序的参数,在两个文件中,一个是名为“archivo”的常规文件和一个名为“carpeta”的文件夹。当它应该是 0 和 1 时,我的程序从文件和文件夹打印 1 和 1。我看不出错误在哪里。

在终端中运行的 stat 函数给出了文件和文件夹的输出。

Fichero: «archivo»
Tamaño: 0 Bloques: 0 Bloque E/S: 4096 fichero regular
Dispositivo: 805h/2053d Nodo-i: 3159580 Enlaces: 1
Acceso: (0664/-rw-rw-r--) Uid: ( 1000/alejandro) Gid: ( 1000/alejandro)
Acceso: 2013-10-31 21:08:57.556446728 -0300
Modificación: 2013-10-31 21:08:57.556446728 -0300
Cambio: 2013-10-31 21:08:57.556446728 -0300
Creación: -

Fichero: «carpeta/»
Tamaño: 4096 Bloques: 8 Bloque E/S: 4096 directorio
Dispositivo: 805h/2053d Nodo-i: 3147783 Enlaces: 2
Acceso: (0775/drwxrwxr-x) Uid: ( 1000/alejandro) Gid: ( 1000/alejandro)
Acceso: 2013-10-31 21:19:11.728526599 -0300
Modificación: 2013-10-31 21:19:20.867833586 -0300
Cambio: 2013-10-31 21:19:20.867833586 -0300
Creación: -

最佳答案

问题是 file->d_name 只是一个文件名,它不包括目录路径。所以 isdir() 正在寻找当前目录中的文件,而不是 argv[1] 中指定的目录。您需要将目录传递给 isdir(),然后在调用 stat() 之前用 / 分隔符将目录和文件名连接起来>.

int isdir(const char *dirname, const char *filename) {
struct stat st_buf;
char *fullname = malloc(strlen(dirname)+strlen(filename)+2); // +2 for the slash and trailing null
strcpy(fullname, dirname);
strcat(fullname, "/");
strcat(fullname, filename);
if (stat(fullname, &st_buf) == -1) {
perror(fullname);
free(fullname);
return 0;
}
free(fullname);
return !S_ISDIR(st_buf.st_mode);
}

那么你应该调用它:

isdir(argv[1], file->d_name));

关于c - 获取文件详细信息时出现错误结果 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19719164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com