ifstream 始终将"ELF"返回到对象

ifstream always returns "ELF" to object

本文关键字:返回 对象 ELF ifstream      更新时间:2023-10-16

我写了下面的方法来检查我的程序是否正确地处理文件IO,但它绝对不起作用。我从inFile得到的都是"ELF",有人能告诉我为什么吗?我的对象可以很好地与其他类型的流兼容。

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]

您指定的是程序名,而不是第一个参数作为文件名。

检查你所做事情的有效性是个好主意。ie。检查args[1]是否为空和/或file open…仅检查参数计数是不够的。