我编写了以下方法来检查我的程序是否与文件IO一起正常工作,但它绝对不起作用。我从inFile得到的只是“ELF”,谁能告诉我为什么?我的对象与其他类型的istreams完美搭配。
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();
}
答案 0 :(得分:8)
args [0] 不是程序的第一个参数。它是可执行文件本身的名称。
正在发生的是您打开自己的可执行文件,而不是命令行中指定的文件,并且因为您的程序是Linux二进制文件,所以您在ELF二进制文件的开头读取魔术字符串,这是“ELF”。
要修复错误,请将args [0]更改为args [1]。
答案 1 :(得分:0)
您正在指定程序名称而不是第一个参数作为文件名。
检查U的有效性是个好主意。即。检查args[1]
是否为空和/或文件的返回值是否打开...仅检查参数计数是不够的。