我需要找到一种方法来扫描文件夹(例如-C:\Users\User\Documents\HW)并检查是否有从用户那里收到的文本。我需要返回哪些文件具有完全相同的文本。我以前从未使用过 dirent.h,而且我不知道如何使用它;
最佳答案
您定义自己的error
函数来处理错误:
// Standard error function
void fatal_error(const char* message) {
perror(message);
exit(1);
}
遍历函数主要是统计当前文件,如果该文件是目录,我们将进入该目录。在目录本身中非常重要的是检查当前目录是否是 .或 .. 因为这可能会导致不定式循环。
void traverse(const char *pathName){
/* Fetching file info */
struct stat buffer;
if(stat(pathName, &buffer) == -1)
fatalError("Stat error\n");
/* Check if current file is regular, if it is regular, this is where you
will see if your files are identical. Figure out way to do this! I'm
leaving this part for you.
*/
/* However, If it is directory */
if((buffer.st_mode & S_IFMT) == S_IFDIR){
/* We are opening directory */
DIR *directory = opendir(pathName);
if(directory == NULL)
fatalError("Opening directory error\n");
/* Reading every entry from directory */
struct dirent *entry;
char *newPath = NULL;
while((entry = readdir(directory)) != NULL){
/* If file name is not . or .. */
if(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")){
/* Reallocating space for new path */
char *tmp = realloc(newPath, strlen(pathName) + strlen(entry->d_name) + 2);
if(tmp == NULL)
fatalError("Realloc error\n");
newPath = tmp;
/* Creating new path as: old_path/file_name */
strcpy(newPath, pathName);
strcat(newPath, "/");
strcat(newPath, entry->d_name);
/* Recursive function call */
traverse(newPath);
}
}
/* Since we always reallocate space, this is one memory location, so we free that memory*/
free(newPath);
if(closedir(directory) == -1)
fatalError("Closing directory error\n");
}
}
您也可以使用chdir()
函数来完成此操作,这样可能更容易,但我想向您展示这种方式,因为它非常具有说明性。但遍历文件夹/文件层次结构的最简单方法是 NFTW 函数。请务必在 man
页面中进行检查。
如果您还有任何疑问,请随时提问。
关于c - 如何使用C中的直接 header 扫描文件夹中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236895/