用于列出目录文件的C代码不起作用

问题描述

我正在使用Windows 10平台,并使用VS buildtools编译了以下C代码。该代码尝试在给定位置列出文件/文件夹。编译进行得很好,但是我没有得到预期的结果。该程序将写入消息“正在列出文件...”,等待一段时间并退出。我在这里做什么错了?

#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;
}

解决方法

有两个问题。

首先,由于char* path = strcat(argv[1],"/*"); path,因此您无法通过argv[1]将连接字符串分配给const char *

第二,当您使用WIN32_FIND_DATAA*时,没有可用的存储空间,因此无法获取返回的数据。

这是修改后的示例:

#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,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;
}

输出:

enter image description here