如何使用其d_name打开目录

问题描述 投票:0回答:1

我列出目录,然后要打开其中一项的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++ file-handling
1个回答
2
投票

将呼叫转移到c_str()d_name是一个字符数组(C样式字符串),而不是std::string类型。

© www.soinside.com 2019 - 2024. All rights reserved.