listing files in a folder using C in Windows

后端 未结 3 479
走了就别回头了
走了就别回头了 2021-01-29 05:21

I want to list the files in this folder \"C:\\home\\WORK\\Desktop\\Communication\". There are ten files in this folder. My code has no error but it\'s not printing anything. Wh

3条回答
  •  轮回少年
    2021-01-29 05:57

    There are a few things wrong with your code.

    1. strcat_s can't append "\\*" to your path char array. The buffer only has enough room for storing the string literal.
    2. I'm uncomfortable with letting you declare a buffer files that has only enough memory to fit all the file names. What happens if you add one more file? Then the buffer is overrun. However, it will still technically work in this scenario.
    3. This line printf("%s\n",files[numberOfFiles]); is undefined behavior. You incremented numberOfFiles to a location in the array that has not been initialized, so it's not going to print the file name.
    4. When you call FindClose, you invalidate all of those pointers that you stored in files. You can no longer use them. You need to copy the string to a new buffer.

    The following code works.

    #include
    #include
    #include
    
    int main(int argc,char *argv[])
    {
        char path[] = "C:\\home\\WORK\\Desktop\\Communication\\*.*";
        //strcat_s(path,sizeof(path),"\\*");
    
        WIN32_FIND_DATA fdata;
        HANDLE hFind =INVALID_HANDLE_VALUE;
        int numberOfFiles=0;
        char* files[10]; /* you may want to expand this buffer */
    
        hFind = FindFirstFile(path,&fdata);
    
        while((FindNextFile(hFind,&fdata))!=0)
        {
            size_t len = strlen(fdata.cFileName);
            files[numberOfFiles] = malloc(len + 1 * sizeof*files); // len + 1 for null-terminator
            strcpy_s(files[numberOfFiles], len, fdata.cFileName);
    
            printf("%s\n",files[numberOfFiles]);
            numberOfFiles++; /* increment this AFTER you print files[numberOfFiles] */
        }
    
        FindClose(hFind);
    
        for(int i = 0; i < (sizeof(file)/sizeof(*file)); ++i) {
            free(file[i]);
        }
    
        return 0;
    }
    

提交回复
热议问题