c++中的fstream错误

fstream error in C++

本文关键字:错误 fstream 中的 c++      更新时间:2023-10-16

我真的需要你的帮助。似乎我不能在c++中做文件操作。我使用fstream来做一些文件操作,但是当我编译它时,出现一个错误说:

|63|error: no matching function for call to 'std::basic_fstream<char>::open(std::string&, const openmode&)'|

我犯了什么错?

下面是部分源代码:

#include<stdio.h>
#include<iostream>
#include<fstream>
#include<string>    
using namespace std;
inline int exports()
{
string fdir;
// Export Tiled Map
cout << "File to export (include the directory of the file): ";
cin >> fdir;
fstream fp; // File for the map
fp.open(fdir, ios::app);
if (!fp.is_open())
    cerr << "File not found. Check the file a file manager if it exists.";
else
{
    string creator, map_name, date;
    cout << "Creator's name: ";
    cin >> creator;
    cout << "nMap name: ";
    cin >> map_name;
    cout << "nDate map Created: ";
    cin >> date;
    fp << "<tresmarck valid='true' creator='"+ creator +"' map='"+ map_name +"'   date='"+ date +"'></tresmarck>" << endl;
    fp.close();
    cout << "nCongratulations! You just made your map. Now send it over to tresmarck@gmail.com for proper signing. We will also ask you questions. Thank you.";
}
return 0;
}

在c++ 11中增加了接受std::string类型作为文件名的fstream::open()。使用-std=c++11标志编译或使用fdir.c_str()作为参数(传递const char*代替)。

请注意,如果提供了文件名,fstream()构造函数可以打开文件,这将消除对fp.open()的调用:
if (std::cin >> fdir)
{
    std::fstream fp(fdir, std::ios::app); // c++11
    // std::fstream fp(fdir.c_str(), std::ios::app); // c++03 (and c++11).
    if (!fp.is_open())
    {
    }
    else
    {
    }
}

您需要启用std::basic_fstream<char>::open(std::string&, const openmode&)过载的c++ 11模式

将其中一个传递给gcc:

-std=c++11-std=c++0x

在c++ 11之前,istream::open函数只接受C字符串。(你可以这样称呼它fp.open(fdir.c_str(), ios::app);)