#define FILE_PATH "E:/demo.txt"
char *StrToUpper(char *str)
{
char *p = str;
while (*p)
{
if (*p >= "a" && *p <= "z")
{
*p -= "a" - "A";
}
p++;
}
return str;
}
char *GetExtension(char *file)
{
char *p = file;
while (*p)
{
p++;
}
while (*p != ".")
{
p--;
}
return p;
}
void GetFileBy_findnext(char *path, char *filter, char *extension)
{
FILE *fp; //文件指针
fp = fopen(FILE_PATH, "wt+");
// 判断文件能否能够正确创建/打开
if (fp == NULL) {
perror(FILE_PATH);
exit(1);
}
struct _finddata_t find_data;
long handle;
char buf[1000];
char search[1000];
char *p;
strcpy(buf, path);
p = buf;
while (*p)
{
p++;
}
p--;
if (*p != "\")
{
strcat(buf, "\");
}
strcpy(search, buf);
strcat(search, filter);
handle = _findfirst(search, &find_data);
if (handle == -1)
{
_findclose(handle);
return;
}
while (!_findnext(handle, &find_data))
{
if (strcmp(find_data.name, ".."))
{
if (find_data.attrib & _A_SUBDIR)
{
char buf1[1000];
char buf2[] = "Windows";
strcpy(buf1, find_data.name);
if (!strcmp(StrToUpper(buf1), StrToUpper(buf2)))
{
continue;
}
strcpy(buf1, buf);
strcat(buf1, find_data.name);
GetFileBy_findnext(buf1, filter, extension);
}
else
{
char buf1[100];
char buf2[100];
strcpy(buf1, GetExtension(find_data.name));
strcpy(buf2, GetExtension(extension));
if (!strcmp(StrToUpper(buf1), StrToUpper(buf2)))
{
fprintf(fp, "%s%s\n", buf, find_data.name);
printf("%s%s\n", buf, find_data.name);
//fflush(fp);
}
}
}
}
fclose(fp);
_findclose(handle);
}
int main()
{
GetFileBy_findnext("C:\", "*.*", "*.exe");
}
程序可以将信息输出到控制台,就是printf可以用,但是fprintf用不了,文件中没有信息
解决方案
25
system(“dir /b /a-d c:\*.* >d:\allfiles.txt”);
//读文件d:\allfiles.txt的内容即C:\下全部文件的名字
system(“dir /b /a-d /s c:\*.* >d:\allfilesinsub.txt”);
//读文件d:\allfilesinsub.txt的内容即C:\下全部文件的名字包含子目录
system(“dir /b /ad c:\*.* >d:\alldirs.txt”);
//读文件d:\alldirs.txt的内容即C:\下全部子目录的名字
请记住,能用shell命令获取文件、文件夹信息或操作文件、文件夹最好用shell命令获取或操作,而不要用各种API获取或操作,原因是当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。
假如嫌system黑窗口一闪,将system(“…”)替换为WinExec(“cmd /c …”,SW_HIDE);
5
写代码过滤fc命令的输出。
10
本人之前写过一个:http://blog.csdn.net/wangyaninglm/article/details/8668132
CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C语言遍历C盘全部.exe文件并将路径与文件名输出到TXT文件中出现问题!