这是我要移植到最初在 Ubuntu 上编写的 windowsXp 的应用程序的部分代码。
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
int list_files(char *parentdir)
{
DIR *dir;
struct dirent *de = NULL;
char subdirs[1000][1000];
int isubdirs = 0;
char rootdir[1000];
strcpy(rootdir, parentdir);
FILE *fp = fopen("list.txt", "w");
seek:
dir = opendir(rootdir);
if (!dir) {
printf("ERROR: [ %s ]", rootdir);
perror("Couldn't opendir: ");
}
else {
de = readdir(dir);
if (!de) {
printf("ERROR:[ %s ]", rootdir);
perror("Couldn't readdir ");
goto out;
}
if (strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, ".") != 0) {
fprintf(fp, "%s\\%s\n", rootdir, de->d_name);
printf("ADDED: %s\\%s\n", rootdir, de->d_name);
}
while ((de = readdir(dir)) != NULL)
{
if (!strcmp(de->d_name, "..") || !strcmp(de->d_name, "."))
continue;
fprintf(fp, "%s\\%s\n", rootdir, de->d_name);
printf("ADDED: %s\\%s\n", rootdir, de->d_name);
struct stat s;
stat(de->d_name, &s);
if (S_ISDIR(s.st_mode))
{
strcpy(subdirs[isubdirs], rootdir);
strcat(subdirs[isubdirs], "\\");
strcat(subdirs[isubdirs], de->d_name);
printf("%s\n", subdirs[isubdirs]);
isubdirs++;
}
/* Not working in WinXP
if (de->d_type == 4) {
strcpy(subdirs[isubdirs], rootdir);
strcat(subdirs[isubdirs], "/");
strcat(subdirs[isubdirs], de->d_name);
isubdirs++;
}
*/
}
if (isubdirs > 0) {
strcpy(rootdir, subdirs[--isubdirs]);
goto seek;
}
}
out:
fclose(fp);
return 0;
}
现在问题出在我得到的输出文件中:
C:\Documents and Settings\user\Desktop\New Folder\00.txt
C:\Documents and Settings\user\Desktop\New Folder\1
C:\Documents and Settings\user\Desktop\New Folder\2
仅列出了 parentdir 中的文件,但未列出子目录(1 和 2 都不是空的“文件夹”)我在 Virtualbox 中进行测试。