如何解决用于列出目录文件的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;
}
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。