优化字符串指针数组

时间:2014-01-25 23:31:30

标签: c arrays string pointers directory

我正在通过一个目录并将多个文件名存储到一个字符串指针数组中。问题是我不知道有多少我可能存储,直到我完全通过目录。以下是我目前设置的方式。

char *dArr[512];
..
..
int i = 0;
while ((derent = readdir(directory)) != NULL) {
..
dArr[i] = derent->d_name;
i++;

该目录可以返回0-1个文件或1000+以上的文件,那么有没有更好的方法来存储这些不知道大小的文件?

2 个答案:

答案 0 :(得分:0)

这是我很久以前实现它的方式,虽然它解决了两个“扫描”中的问题(而不是一个,正如你可能在你的问题中所针对的那样):

#include <io.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    int    fileCount; //The number of files in the current directory
    char*  fileIsDir; //An array of sub-dir flags (for each file)
    char** fileNames; //An array of names (for each file)
}
Directory;

void Open(Directory* directory)
{
    int    fileCount = 0;
    char*  fileIsDir = 0;
    char** fileNames = 0;

    int i;
    int handle;
    struct _finddata_t file;

    handle = _findfirst("*.*",&file);
    while (_findnext(handle,&file) == 0)
        fileCount++;
    _findclose(handle);

    fileIsDir = (char* )malloc(fileCount*sizeof(char ));
    fileNames = (char**)malloc(fileCount*sizeof(char*));

    handle = _findfirst("*.*",&file);
    for (i=0; i<fileCount; i++)
    {
        _findnext(handle,&file);
        fileIsDir[i] = (file.attrib&_A_SUBDIR)!=0;
        fileNames[i] = (char*)malloc(strlen(file.name)+1);
        strcpy(fileNames[i],file.name);
    }
    _findclose(handle);

    directory->fileCount = fileCount;
    directory->fileIsDir = fileIsDir;
    directory->fileNames = fileNames;
}

void Close(Directory* directory)
{
    int    fileCount = directory->fileCount;
    char*  fileIsDir = directory->fileIsDir;
    char** fileNames = directory->fileNames;

    int i;
    for (i=0; i<fileCount; i++)
        free(fileNames[i]);

    if (fileNames)
        free(fileNames);

    if (fileIsDir)
        free(fileIsDir);
}

答案 1 :(得分:0)

如果你需要一个非常简单的动态增长结构,这里还有一些示例代码:

#include <stdio.h>    
#include <stdlib.h>    

struct mybuf {
    int bufsz;
    char *buf[1];
};

int test_alloc(int x)
{
    int i;
    struct mybuf *mb;
    // initially alloc buffer which can 
    // at least hold 32 (char *) pointers
    mb = (struct mybuf *)malloc(sizeof(*mb) + 32*sizeof(mb->buf[0]));
    mb->bufsz=32;

    for (i=0;i<x;i++) {
        if (i>=mb->bufsz) {
            // grow buffer size to i*1.5
            mb = realloc(mb,sizeof(*mb) + (i + i/2)*sizeof(mb->buf[0]) );
            mb->bufsz = i + i/2;
        }
        mb->buf[i] = (char *)"Hello World\n";
    }
    for (i=0;i<x;i++) {
        printf(mb->buf[i]);
    }

    free(mb);
}

int main()
{
    test_alloc(100);
    return 0;
}