c++ - 为什么我的 fstream 访问不能编译?

标签 c++ eclipse fstream

我有一个问题。我正在用 C++ 编写一个程序,我想访问一些文件,所以我使用类 fstream。好吧,这里一切正常,但是当我要编译程序时它崩溃并给我一个错误。

我把连接文件的代码放在这里:

#include <iostream>
#include <fstream>
#include <map>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <string.h>

using namespace std;

fstream file1, file2;

void access();

int main(){
   access();

   file1.close();
   file2.close();
}

void access(){

    file1("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);
    cout << "Opening File1..." << endl;

    file2("C:\\data\\file2.dat",ios::in | ios::out | ios::binary);
    cout << "Opening File2..." << endl;

}

它给了我以下错误:

no match for call to '(std::fstream {aka std::basic_fstream<char>}) (const char [20], std::_Ios_Openmode)'

所以我试着像这样访问方法:

void access(){
        string f1 = "C:\\data\\file1.dat";
        string f2 = "C:\\data\\file2.dat";


        file1(f1.c_str(),ios::in | ios::out | ios::binary);
        cout << "Opening File1..." << endl;

        file2(f2.c_str(),ios::in | ios::out | ios::binary);
        cout << "Opening File2..." << endl;

    }

但它也给我一个错误。其内容如下:

no match for call to '(std::fstream {aka std::basic_fstream<char>}) (const char*, std::_Ios_Openmode)'

我不知道会发生什么,任何帮助将不胜感激。

非常感谢。

最佳答案

即使它看起来像,但这不是对构造函数的调用,因为它已经在全局空间中声明和构造。

file1("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);

这是对 operator() 的调用。尝试使用 open 代替:

file1.open("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);

关于c++ - 为什么我的 fstream 访问不能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28929665/

相关文章:

c++ - 如何在 C++ 中同时写入和读取 `fstream` 的文件?

c++ - 我的函数无法正确编译

c++ - 调试 MMC(非托管 C++)?

java - 如何不将某些目录/文件推送到Github?

java - 请帮助解决从 ant/jar 构建迁移旧项目时出现的 Maven 困惑问题

c++ - 我应该期望 CentOS6 和 CentOS7 之间 fstream 异常处理的不同行为吗?

c++ - 为什么我们使用模板而不是函数?

c++ - 稀疏矩阵超定线性方程组c/c++库

java - 如何在 eclipse 中将 .war 文件作为 java web 项目依赖项包含在内?

C++ 文件处理 - 输出与输入不匹配