簡體   English   中英

如何在 C 中讀取文件目錄以獲取所有非文件夾文件的名稱

[英]How do I read a file directory in C to get the Names of all non-folder files

我正在嘗試讀取給定的目錄 filePath 並將所有非文件夾文件的名稱放入字符串數組中。 所以我需要解決的問題是如何專門不獲取文件夾類型文件,但也獲取所有其他文件類型名稱並將它們存儲到字符串數組中。 稍后我還計划使用線程來讀取這些單獨的文件,但我需要能夠正確存儲文件名。 我目前使用的代碼如下。 還應該注意的是,此代碼正在由 fork() 命令的子進程執行,但我不確定這是否與問題有關。 任何幫助,將不勝感激。 謝謝。

示例:在 Home/Documents 中有 4 個文件:hello.txt something.dat folder1 something2.dat

我的字符串數組應該有值 hello.txt、something.dat 和 something2.dat

注意:我可以在瀏覽目錄時不做這些文件,因為文件本身在所有內容上都不會被更改。

//char* directory is an absolute filePath to the directory
void getFilesFromDirectory(char* directory, pid_t process)
{
    int index =0;
    DIR *dir;
    struct dirent *ent;
    //Can hold only 500 valid files in the folder
    char *stringArray[500];
    if ((dir = opendir (directory)) != NULL) 
    {
        while ((ent = readdir (dir)) != NULL) 
        {            
            strcpy(stringArray[index],ent->d_name);
            index++;         
        }
        closedir (dir);
    } 
    else 
    {
        /* could not open directory */
         perror ("");
    }

   //Everything Below is not related to the problem. Just what I am using it for.

    pthread_t threadArray[index];
    pthread_t senderThread;
    //thread_param_t parameterSender;
    thread_param_t paramterArray[index];

    sem_init(&empty,0,bufferSize);
    sem_init(&full, 0, 0);
    sem_init(&mutex, 0, 1);

    //parameterSender.listItem = listHead;
    pthread_create(&senderThread, NULL, senderFunction, NULL);
    //int threadCounter = 0;
    for(int i =0; i<index; i++)
    {
        paramterArray[i].fileLocation = strcat(directory, stringArray[i]);
        pthread_create(&threadArray[i], NULL, threadFunction, paramterArray + i);

    }
}

您可以檢查stringArray中沒有“.”的文件。 並將此指針設置為 Null。 (有文件丟失)

更好的選擇是這樣的:

#include <stdio.h>
#include <dirent.h>


int main()
{
    DIR *folder;
    struct dirent *entry;
    int files = 0;

    folder = opendir(".");
    if(folder == NULL)
    {
        perror("Unable to read directory");
        return(1);
    }
    printf("debug\n");
    while( (entry=readdir(folder)) )
    {
        files++;
        printf("File %3d: %s :: %s\n",
                files,
                entry->d_name,
                (entry->d_type == DT_DIR)?"Directory" : "File"
              );
    }

    closedir(folder);

    return(0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM