我列出目录,然后要打开其中一项的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
类型。