[英]ifstream always returns “ELF” to object
我編寫了以下方法來檢查我的程序是否可以正確地與文件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]。
您正在指定程序名而不是第一個參數作為文件名。
檢查U做的有效性是一個好主意。 即。 檢查args[1]
是否不為空和/或文件的返回值是否打開...僅檢查參數計數是不夠的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.