How can I get the list of files in a directory using C or C++?

前端 未结 27 3162
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  滥情空心
    2020-11-21 06:13

    char **getKeys(char *data_dir, char* tablename, int *num_keys)
    {
        char** arr = malloc(MAX_RECORDS_PER_TABLE*sizeof(char*));
    int i = 0;
    for (;i < MAX_RECORDS_PER_TABLE; i++)
        arr[i] = malloc( (MAX_KEY_LEN+1) * sizeof(char) );  
    
    
    char *buf = (char *)malloc( (MAX_KEY_LEN+1)*sizeof(char) );
    snprintf(buf, MAX_KEY_LEN+1, "%s/%s", data_dir, tablename);
    
    DIR* tableDir = opendir(buf);
    struct dirent* getInfo;
    
    readdir(tableDir); // ignore '.'
    readdir(tableDir); // ignore '..'
    
    i = 0;
    while(1)
    {
    
    
        getInfo = readdir(tableDir);
        if (getInfo == 0)
            break;
        strcpy(arr[i++], getInfo->d_name);
    }
    *(num_keys) = i;
    return arr;
    }
    

提交回复
热议问题