首页 > 解决方案 > 为什么打开带有格式的文件时fstream会导致分段错误?

问题描述

我有以下代码

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unistd.h>
using namespace std;

int main()
{
  ifstream asmfile("asmcode",ifstream::in);

  if(!asmfile)
  {
     cout << "error" << endl;
  }

  return 0;
}

其中“asmcode”只是一个文本文件,与主文件存在于同一目录中。它实际上是一个通过 bash ">dummy.txt" 创建的空文件。

我在 Ubuntu Linux 18.04 上运行它,使用 g++ 9.2.1 作为编译器。

这会在我的机器上打印“错误”。我不知道为什么文件没有被打开。我还注意到,如果我在文件名后面附加文件格式,我会得到一个更奇怪的分段错误。

这里有什么问题?

标签: c++fstream

解决方案


您应该添加文件扩展名,否则程序无法区分两个同名文件。

ifstream asmfile("asmcode.txt", ifstream::in);


推荐阅读