c++ - ifstream 总是返回 "ELF"给对象

标签 c++ file-io io fstream ifstream

我编写了以下方法来检查我的程序是否可以正确处理文件 IO,但它肯定不起作用。我从 inFile 得到的都是“ELF”,谁能告诉我为什么?我的对象与其他类型的 istream 一起工作得很好。

void testFiles(int ct, char ** args)
{
    if(ct<2){
        cout<<"Invalid number of arguments. Must be two files, one for input, one for output."<<endl;
        return;
    }
    ifstream inFile;
    inFile.open(args[0]);
    Tree<Word,int> x;
    Word *key;
    Word *val;
    cout<<"Tree extracted from file: "<<endl;
    while(inFile.good()&&inFile.is_open()){
        key = new Word();
        val = new Word();
        inFile>>*key;
        inFile>>*val;
        if(!inFile.good()){
            cout<<"Error: incomplete key-value pair:"<<key->getStr()<<endl;
            break;
        }
        cout<<key->getStr()<<" "<<val->getStr()<<endl;
        x[*key] = val->asInt();
        delete key;
        delete val;
    }
    inFile.close();
    ofstream outFile;
    outFile.open(args[1]);
    cout<<"Tree as read from file:"<<endl<<x;
    outFile<<x;
    outFile.close();
}

最佳答案

args[0] 不是您程序的第一个参数。它是可执行文件本身的名称。

发生的事情是你正在打开你自己的可执行文件,而不是在命令行上指定的文件,并且由于你的程序是一个 linux 二进制文件,你正在读取 ELF 二进制文件开头的魔术字符串,这是“ELF”。

要修复错误,请将 args[0] 更改为 args[1]。

关于c++ - ifstream 总是返回 "ELF"给对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775078/

相关文章:

在windows 7中创建Java jdk1.8文件

c - fread() 返回读取字节数 + 1

c++ - asio::async_write 在大容量流上同步非常困难

c++ - C++中的64位ntohl()?

c++ - 转换 COM 接口(interface)

python-3.x - 为什么 file.tell() 会影响编码?

c++ - 编译器什么时候不生成移动构造函数和移动赋值?

bash - 在 bash 中编写带有替换的通用文件

c - 文件路径重定向

Haskell 无法将类型 `Stack' 与 `IO' 匹配