现在有一个确定的路径下只放了一个文件,我知道这个文件的路径但是这个路径下的文件名一直在变化,我要如何获取到这个文件的名字呢
#include <iostream>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
const char *path = "/home/user/files/";
if ((dir = opendir(path)) != nullptr) {
while ((ent = readdir(dir)) != nullptr) {
if (ent->d_type == DT_REG) { // DT_REG表示是常规文件
std::cout << "File name: " << ent->d_name << std::endl;
}
}
closedir(dir);
} else {
std::cerr << "Failed to open directory: " << path << std::endl;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __WIN64
#include <windows.h>
#endif
void getFileInf(const char *command)
{
char comLs[128] = "ls ";
strcat(comLs, command);
// 获取windows命令回执
FILE *winCommand = popen(comLs, "r");
static char buf[256] = {};
if (!winCommand)
{
perror("popen");
exit(EXIT_FAILURE);
}
else
{
// 输出命令回执
while (fgets(buf, sizeof(buf) - 1, winCommand) != 0)
{
printf("%s", buf);
memset(buf, 0, sizeof(buf));
}
pclose(winCommand);
}
}
int main()
{
#ifdef __WIN64
SetConsoleOutputCP(65001);
#endif
getFileInf("E:\\C++");
return 0;
}