如何使用目录d_name打开目录

how to open a directory using its d_name

本文关键字:name 何使用      更新时间:2023-10-16

我列出了目录,然后想打开其中一个条目的d_name。
为此,我输入一个整数,即列表中项目的数量。并打开其相应的文件。

我收到此错误:

[Error] request for member 'c_str' in 'ent->dirent::d_name', which is of non-class type 'char [260]'

法典:

#include <bits/stdc++.h>
#include <fstream>
#include <direct.h>
#include <Windows.h>
#include <conio.h>
#include <dirent.h>
using namespace std;
int main(){

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("C:/path")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
cout<<ent->d_name<<endl;
}
}
else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
int z;
cout<<"enter the directory number to open"<<endl;
cin>>z;       
int k{1};     // counter variable
dir = opendir ("C:/path")
while ((ent = readdir (dir)) != NULL) {
if(z==k){
system((ent->d_name).c_str());
break;
}
k++;
}
}

删除对c_str()的调用。d_name是字符数组(C 样式字符串(,而不是std::string类型。