我正在尝试创建一个C语言函数,扫描我所有的路径C:\temp(Windows),以查找我传递的文件(例如test.txt),每次找到一个文件时返回该文件的路径,然后将其传递给另一个函数,在该文件的底部写入一些内容。我已经成功实现了写入文件的函数,但是不知道如何扫描文件夹并传递找到的文件地址。
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done.\n");
exit(0);
}
int main(){
printf("扫描/home目录:\n");
printdir("C:/LOG/Filter.txt",0);
printf("完成。\n");
exit(0);}
- AleMalchdir(dir);
可以工作,但是最后的 chdir("..");
不是“返回到您所在的目录”的通用解决方案。我认为它只适用于命名目录是当前目录的直接子目录的情况。在 POSIX 系统上,可以使用 fchdir()
安全地更改目录:在进行初始的 chdir()
之前,int cwd = open(".", O_RDONLY);
打开当前目录,然后 fchdir(cwd)
返回到该目录,然后当然要跟随 close(cwd)
。 - Jonathan Leffler