2

Windows PC のフォルダーをスキャンする関数を作成しようとしていますが、そのたびに「Filter.txt」というファイルに「Test Script」という文字列が追加されます。

fopen問題は 2 です。1 つ目は、ディレクトリ c:\LOG またはそのサブディレクトリでスキャンを実行する必要があることです。2 つ目は、ディレクトリとファイル名を連鎖させる方法がわからないことです。

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);
    }
}

編集opendirおよびreaddir関数は、Windows ではあまりサポートされていないようです。上記の例と同様に、Windows のみを使用しますFindFirstFile。これらの関数の使用方法の例については、この MSDN ページFindNextFileを参照してください。

于 2011-11-16T13:03:07.610 に答える