简体   繁体   中英

C code for listing files of a directory is not working

I am using Windows 10 platform and compiled the following C code using the VS buildtools. The code attempts to list file/folders at a given location. Compilation went fine, but I am not getting the desired results. The program writes the message 'Listing files ...', waits for some time and exits. What am I doing wrong here?

#include <stdio.h>
#include <windows.h>
#include <string.h>


int main(int argc, char* argv[]){

HANDLE fhandle;
WIN32_FIND_DATAA* file_details;
int next_file = 1;

char* path = strcat(argv[1], "/*"); 
printf("Listing files for %s\n", path);
fhandle = FindFirstFileA(path, file_details);

if(fhandle != INVALID_HANDLE_VALUE){
    
    while(next_file){
        printf("%s\n", file_details->cFileName);
        next_file = FindNextFileA(fhandle, file_details);   
    }
        
}
else{
    printf("Error!");
}

FindClose(fhandle);
return 0;
}

There are two problems.

First of all, you cannot pass char* path = strcat(argv[1], "/*"); assign a concatenated string to path , because argv[1] is a const char * .

Second, when you use WIN32_FIND_DATAA* , there is no memory space for it, so it cannot get the returned data.

Here is the modified example:

#include <stdio.h>
#include <windows.h>
#include <string.h>


int main(int argc, char* argv[]) {

    HANDLE fhandle;
    WIN32_FIND_DATAA* file_details = (WIN32_FIND_DATAA*)malloc(sizeof(WIN32_FIND_DATAA));
    memset(file_details, 0, sizeof(WIN32_FIND_DATAA));
    int next_file = 1;
    char path[100];
    strcpy(path, argv[1]);
    strcat(path, "/*");
    printf("Listing files for %s\n", path);
    fhandle = FindFirstFileA(path, file_details);

    if (fhandle != INVALID_HANDLE_VALUE) {

        while (next_file) {
            printf("%s\n", file_details->cFileName);
            next_file = FindNextFileA(fhandle, file_details);
        }

    }
    else {
        printf("Error!");
    }
    free(file_details);
    FindClose(fhandle);
    return 0;
}

Output:

在此处输入图片说明

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