C语言-读取一个目录中的文件,并将文件名写入数组
注意点:
- 文件名是字符串,放入数组,需要数组二维数组,
array[m][n], m表示字符串的个数,n表示字符串的长度
; - 使用函数
char* strcpy(char* destination,const char* source)
,
例如:
char strings[3][10];
strcpy(strings[0], "hello");
完成代码如下:
# include <stdio.h>
#include <iostream>
#include <fstream>
# include <io.h>
# include <string.h>
using namespace std;
void findfile(string path, string mode)
{
char origFileName[1000][1000] = { 0 };
uint32_t fileCount = 0;
uint32_t i = 0;
_finddata_t file;
intptr_t HANDLE;
string Onepath = path + mode;
HANDLE = _findfirst(Onepath.c_str(), &file);
if (HANDLE == -1L)
{
cout << "can not match the folder path" << endl;
system("pause");
}
do {
//判断是否有子目录
if (file.attrib & _A_SUBDIR)
{
//判断是否为"."当前目录,".."上一层目录
if ((strcmp(file.name, ".") != 0) && (strcmp(file.name, "..") != 0)) //比较字符串自str1和str2是否相同。如果相同则返回0;
{
string newPath = path + "\\" + file.name;
findfile(newPath, mode);
}
}
else
{
cout << file.name << " " << endl;
printf("%d: %s\n", i, file.name);
strcpy(origFileName[i], file.name);
}
fileCount ++;
i++;
} while (_findnext(HANDLE, &file) == 0);
_findclose(HANDLE);
printf("files total: %d\n", fileCount);
for (int j = 0; j < fileCount; j++){
printf("file name: %s\n", origFileName[j]);
}
}
int main(int argc, char **argv)
{
string mode = "\\*.txt";
string path = "F:\\text";
findfile(path, mode);
system("pause");
return 0;
}
结果显示: