2

我正在尝试创建一个扫描 Windows PC 上的文件夹的函数,每次扫描时,都会在一个名为“Filter.txt”的文件中附加字符串“Test Script”。

现在的问题是2,第一个是扫描必须在目录c:\LOG或其子目录中执行,第二个是我不知道如何链接fopen目录和文件名。

int main(){
    DIR *dir;
    FILE * pFile;
    char myString[100];
    struct dirent *ent;
    dir = opendir ("c:\\LOG");
    if (dir != NULL) {
        /* print all the files and directories */
        while ((ent = readdir (dir)) != NULL) {
            pFile = fopen ("Filter.txt","a");
            if (pFile==NULL)
                perror("Error");  
            else
                fprintf(pFile,"%s\n","Test scriptIno");
            fclose(pFile);
            //printf ("%s\n", ent->d_name);
        }
        closedir (dir);
    } else {
        /* Can not open directory */
        perror ("");
        return EXIT_FAILURE;
    }
}
4

1 回答 1

1

对于如何将呼叫链接到opendir您可以在 SO 上找到很多答案,例如this。用于ent->d_type检查条目是目录还是文件。

要打开目录中的文件,只需使用路径名ent->d_name来构造fopen调用的路径。

编辑工作有点无聊,做了一个你可能想要的功能......

#ifdef _WIN32
# define DIR_SEPARATOR "\\"
#else
# define DIR_SEPARATOR "/"
#endif
void my_readdir(const char *path)
{
    DIR *dir = opendir(path);
    if (dir != NULL)
    {
        struct dirent *ent;

        static const char filtername[] = "filter.txt";

        /* +2: One for directory separator, one for string terminator */
        char *filename = (char *) malloc(strlen(path) + strlen(filtername) + 2);

        strcpy(filename, path);
        strcat(filename, DIR_SEPARATOR);
        strcat(filename, filtername);

        FILE *fp = fopen(filename, "a");

        while ((ent = readdir(dir)) != NULL)
        {
            if (ent->d_type == DT_REG || ent->d_type == DT_DIR)
            {
                if (strcmp(ent->d_name, "..") != 0 && strcmp(ent->d_name, ".") != 0)
                {
                    if (fp != NULL)
                        fprintf(fp, "%s : %s\n", (ent->d_type == DT_REG ? "File" : "Directory"), ent->d_name);

                    if (ent->d_type == DT_DIR)
                    {
                        /* +2: One for directory separator, one for string terminator */
                        char *newpath = (char *) malloc(strlen(path) + strlen(ent->d_name) + 2);

                        strcpy(newpath, path);
                        strcat(newpath, DIR_SEPARATOR);
                        strcat(newpath, ent->d_name);

                        /* Call myself recusively */
                        my_readdir(newpath);

                        free(newpath);
                    }
                }
            }
        }

        if (fp != NULL)
            fclose(fp);
        free(filename);
    }
}

编辑Windows 上似乎不太支持opendirand功能。readdir仅使用 Windows,FindFirstFileFindNextFile以与我上面的示例类似的方式使用。有关如何使用这些功能的示例,请参阅此 MSDN 页面。

于 2011-11-16T13:03:07.610 回答