任何人都可以发现我在这里缺少什么吗?该代码块应该递归访问目录并存储目录路径和其中文件的路径。如果文件是目录,它将 fprintf() 为 true,如果文件不是目录,则为 false。奇怪的是,fileName 的 printf 例程工作正常,但是当将 fprintf fileName 打印到文件时,它只是在应该打印 fileName 的地方打印一个换行符。
/* List the files in "dir_name". */
static void listDir(const char *dirName)
{
DIR *dir;
/*
* Open the directory specified by "dirName".
*/
dir = opendir(dirName);
/*
* Check it was opened.
*/
if (!dir) {
fprintf(stderr, "Cannot open directory '%s': %s\n",
dirName, strerror(errno));
exit(EXIT_FAILURE);
}
while (1) {
struct dirent *entry;
const char *dir_name;
/*
* "Readdir" gets subsequent entries from "d".
*/
entry = readdir(dir);
if (!entry) {
/*
* There are no more entries in this directory, so break out of the while loop.
*/
break;
}
dir_name = entry->d_name;
char fileName[PATH_MAX];
// Assign fileName to path if the file is not a directory
if (entry->d_type != DT_DIR) {
if (strcmp(dirName, "/") != 0) {
snprintf(fileName, PATH_MAX,
"%s/%s", dirName, dir_name);
} else {
snprintf(fileName, PATH_MAX,
"%s%s", dirName, dir_name);
}
}
/* Access directory and leave out /. and /.. in the process
*/
if (entry->d_type == DT_DIR) {
/*
* Check that the directory is not "d" or d's parent.
*/
if (strcmp(dir_name, "..") != 0 && strcmp(dir_name, ".") != 0) {
int path_length;
char path[PATH_MAX], indexPath[PATH_MAX];
if (strcmp(dirName, "/") != 0) {
path_length = snprintf(path, PATH_MAX,
"%s/%s", dirName, dir_name);
} else {
path_length = snprintf(path, PATH_MAX,
"%s%s", dirName, dir_name);
}
strcpy(indexPath, path);
strcat(indexPath, "/masterIndex.db");
FILE *fp;
if ((fp = fopen(indexPath, "a")) == NULL) {
printf("Cannot open file\n");
return;
}
printf("File: %s\n (TRUE)\n", path);
printf("File: %s\n (FALSE)\n", fileName); // This routine prints fileName correctly
fprintf(fp, "%s\n", path);
fprintf(fp, "%s\n", "true");
fprintf(fp, "%s\n", fileName); // This routine prints a newline where fileName is supposed to be
fprintf(fp, "%s\n", "false");
fclose(fp);
// Activate this for screw ups
/*
char command[PATH_MAX];
strcpy(command, "cd ");
strcat(command, path);
strcat(command, " && rm abc *.finderDB .DS_Store");
printf("%s\n", command);
system(command);*/
if (path_length >= PATH_MAX) {
fprintf(stderr, "Path length has gotten too long.\n");
exit(EXIT_FAILURE);
}
/*
* Recursively call "list_dir" with the new path.
*/
listDir(path);
}
}
}
/*
* After going through all the entries, close the directory.
*/
if (closedir(dir)) {
fprintf(stderr, "Could not close '%s': %s\n",
dirName, strerror(errno));
exit(EXIT_FAILURE);
}
}