简体   繁体   中英

ifstream always returns “ELF” to object

I wrote the following method to check whether my program works correctly with file IO, but it most definitely doesn't work. All that I get from inFile is "ELF", can anyone tell me why? My objects work perfectly fine with other types of 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();
}

args[0] is not the first argument to your program. It's the name of the executable file itself.

What's happening is that you're opening your own executable file, rather than the file specified on the command line, and since your program is a linux binary, you're reading in the magic string at the start of ELF binaries, which is "ELF".

To fix the error, change args[0] to args[1].

You are specifying the program name instead of the first param as a file name.

It is a good idea to check for the validity of what U do. ie. check either whether the args[1] is not empty and/or the return value of file open... Only checking the parameter count is not enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM