使用变量名打开文件

Opening a file using a variable name

本文关键字:文件 变量名      更新时间:2023-10-16

如果我将myfile("input.txt")更改为myfile(file_name)…其中file_name传递给函数,它不起作用,但给出错误没有匹配的函数调用…我猜b.c.我不应该传递字符串给构造函数…如果不是这样,怎么做?

void file_to_string(string file_name)
{
   string line;  
   ifstream myfile("input.txt");
   if(myfile.is_open())
   {
      while(myfile.good())
      {
         getline(myfile,line);
         cout << line;
      }
      myfile.close();
  }
  else
  {
      cout << "File : " << file_name << " : did not open" ;
  }
}
int main(int argc, char *argv[])
{
    file_to_string(argv[1]);
}

使用std::string类中的c_str()成员:

ifstream myfile(file_name.c_str());

它返回一个以空结束的const char *表示的字符串,这正是你在这里需要的。

file_namestd::string,但ifstream构造函数想要一个普通的c风格字符串(指向char的指针)。所以使用:

iftsream myfile(file_name.c_str());

这是库中一个相当不干净的部分,恕我冒犯,因为流库比STL更老(std::string是从STL中提取的)。所以流库并不真正了解std::string。这也是为什么std::getline(std::istream&, std::string&)是一个独立的功能(和<string>的一部分,而不是<istream>或类似的东西),我想。

可以看作是组件的干净分离,但我认为std::string应该是c++中字符串的标准,因此也可以被流库使用(至少它的接口)。由于标准库总是被视为一个整体,因此这只是组件干净地协同工作的一个糟糕示例。也许未来的标准会解决这个问题。

EDIT:根据Benjamin的评论(以及我对标准草案的阅读)c++ 11似乎确实解决了这个问题,你现在可以使用std::string作为文件名。但是我猜你还没有用c++ 11

std::ifstream的构造函数接受文件名为const char*。可以使用c_str()成员函数将std::string类型转换为const char*类型。

 void file_to_string(string file_name)
  {
  string line;  
  ifstream myfile(file_name.c_str()); //convert string to const char*
  if(myfile.is_open())
    {
    while(myfile.good())
      {
      getline(myfile,line);
      cout << line;
      }
    myfile.close();
    }
  else
    {
    cout << "File : " << file_name << " : did not open" ;
    }
  }
int main(int argc, char *argv[])
  {
  file_to_string(argv[1]);
  }

ifstream接受const char*作为参数,因此不能传递std::string给它。也许你可以试试:

 std::string fileName;
 ... // fill fileName
 ifstream myfile( fileName.c_str() );