我编写了以下方法来检查我的程序是否可以正确处理文件 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/