简体   繁体   中英

Save filenames in array in C

I have this function:

void f_listfiles(char temp[200]){
    HANDLE hFind;
    WIN32_FIND_DATA FindData;
    int i;

    hFind = FindFirstFile("*", &FindData);

    while (FindNextFile(hFind, &FindData))
    {
    strcpy(temp, FindData.cFileName);

    }

    FindClose(hFind);
}

I want it to put the filenames in the directory in to char temp. After that i am going to send it to a FTP client. How can i do this? It currently overwrites each time and only the last file is in the char temp.

Edit:I cant use an array of pointers due to the fact that i later need to send this array with the function send(clientSocket, temp, sizeof(temp), 0)

I want it to put the filenames in the directory in to char temp[]

That is not going to work: a character array is a single string; you need an array of strings.

That is, you need an array of pointers. There are several ways of making it work. One is to let the caller pass an array, along with its length to avoid overruns, and then allocate strings dynamically as you go. You need to return how many entries you filled in, otherwise the caller would not know where in his array the actual file names end.

size_t f_listfiles(char *names[], size_t max) {
    HANDLE hFind;
    WIN32_FIND_DATA FindData;
    size_t i = 0;
    hFind = FindFirstFile("*", &FindData);
    while (FindNextFile(hFind, &FindData) && i != max)
    {
        names[i] = malloc(strlen(FindData.cFileName)+1);
        strcpy(names[i], FindData.cFileName);
        i++;
    }
    FindClose(hFind);
    return i;
}

The caller would call your function like this:

char *names[200];
size_t count = f_listfiles(names, 200);
for (size_t i = 0 ; i != count ; i++) {
    printf("%02d: %s\n", i+1, names[i]);
}
// Caller needs to free dynamically allocated strings:
for (size_t i = 0 ; i != count ; i++) {
    free(names[i]);
}

I later need to send this array to a client

The code that sends this array would need to serialize it in some way - say, append strings one by one to a character buffer before sending.

Besides the fact that temp maybe too small to handle or the strings you can do the following to overcome the overwrite problem:

int i = 0;
while (FindNextFile(hFind, &FindData))
{
    if(i == 0){
        strcpy(temp, FindData.cFileName);
        i++;
        continue;
    }

    strcat(temp, FindData.cFileName);
}

or

temp[0] = 0; //terminating null character so strcat can join the strings
while (FindNextFile(hFind, &FindData))
{
    strcat(temp, FindData.cFileName);
}

There is a catch though. The strcat will ovewrite the terminating null character of the temp string and append a new one in the end of the resulting string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM