gpt4 book ai didi

c - 试图读取目录中的文件,目录只会导致他自己并在他自己中循环

转载 作者:行者123 更新时间:2023-12-01 23:22:23 25 4
gpt4 key购买 nike

所以代码思路是这样的:我在main里面选了一个路径,进去,如果遇到一个文件,就把它的名字和修改日期保存在.txt文件里,否则就打开它刚才的目录找到,进入并重新对该目录进行处理

过程的其余部分工作得很好,直到我取消对递归部分的注释,我认为它将继续进入它自己的地方(路径。),然后循环到该状态(转到路径..,路径... , 等), 使这个东西完全没用, 只是一个无限循环

有什么想法吗?

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>

void ecrire(char * s);
void ecrire_add(char * s);
void regarder(char * loc);

int main(void) {
char localisation[10000]="Path example";
ecrire("");
regarder(localisation);
return(0);
}

void ecrire_add(char * s){
FILE * fichiertexte;
fichiertexte = fopen(".\\liste.txt","a");
fputs(s,fichiertexte);
fclose(fichiertexte);
}
void ecrire(char * s){
FILE * fichiertexte;
fichiertexte = fopen(".\\liste.txt","w");
fprintf(fichiertexte,s);
fclose(fichiertexte);
}

void regarder(char * loc){
DIR *d;
struct dirent *dir;
char contenu[100];
char position[100];
char modification[20];
struct stat attrib;
d = opendir(loc);
strcpy(position, loc);
if (d) {
while ((dir = readdir(d)) != NULL) {
if((dir->d_name) !="$WinREAgent" && (dir->d_name) !=".." && (dir->d_name) !="." && (dir->d_name) !="\\."){
strcpy(contenu,dir->d_name);
strcat(position,"\\");
strcat(position,contenu);
stat(position,&attrib);
strftime(modification, 20, "%H:%M:%S %d-%m-%y", localtime(&(attrib.st_mtime)));
//where i think the problem starts
//this is the part i comment to check if the rest is functionnal
if((S_ISDIR(attrib.st_mode)) && (dir->d_name) !=loc){
printf("rentre doss %s \n", position);
regarder(position);
}
//where i think it ends
printf("%s \n", position);
strcat(position,"\n");
strcat(position,modification);
strcat(position,"\n \n");
ecrire_add(position);
strcpy(position,loc);
strcpy(modification,"");
}
}
}
closedir(d);
}

最佳答案

问题出在这里:

if((dir->d_name) !="$WinREAgent" && (dir->d_name) !=".." && (dir->d_name) !="." && (dir->d_name) !="\\.")

在 C 语言中,使用 ==!= 比较字符串比较的是两个字符串的地址,而不是它们的内容。由于字符串文字位于程序的静态数据区域中,并且 d_name 指向分配的内存或 DIR 对象内的暂存缓冲区,因此这些比较始终为假。您必须改用 strcmp。此外,特殊目录条目 . 的名称只是 .,而不是 \.。因此:

if (!strcmp(dir->d_name, "$WinREAgent") ||
!strcmp(dir->d_name, "..") ||
!strcmp(dir->d_name, ".")) {
continue;
}
// what you had inside your if statement goes here

请注意,我翻转了 if 的含义。这只是为了避免另一层缩进。

由于您似乎使用的是 Windows,因此您可能希望使用 strcasecmp 进行第一项比较。您可能还想使用 native Windows API 来扫描目录 (FindFirstFileW/FindNextFileW) 而不是 Unix 兼容层,以便更好地支持非 ASCII 文件名(但这是一个很大的改变)。

我没有检查你的代码是否有其他问题。

关于c - 试图读取目录中的文件,目录只会导致他自己并在他自己中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67843668/

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