为什么fstream在打开带格式的文件时会导致段错误?
Why does fstream causes segmentation fault when opening file with format?
我有以下代码
#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 作为编译器。
这会在我的机器上打印 "error"。我不知道为什么文件没有被打开。我还注意到,如果我在文件名后附加文件格式,我会得到一个更奇怪的分段错误。
这里有什么问题?
您应该添加文件扩展名,否则程序无法区分两个同名文件。
ifstream asmfile("asmcode.txt", ifstream::in);
我有以下代码
#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 作为编译器。
这会在我的机器上打印 "error"。我不知道为什么文件没有被打开。我还注意到,如果我在文件名后附加文件格式,我会得到一个更奇怪的分段错误。
这里有什么问题?
您应该添加文件扩展名,否则程序无法区分两个同名文件。
ifstream asmfile("asmcode.txt", ifstream::in);