简体   繁体   中英

C++ fstream multiple input files

I am writing a simple program to take in two files. The terminal command line looks like this.

./fileIO foo.code foo.encode

When it runs, the second file is not read in. When I enter

./fileIO foo.code foo.code

it works. I can't seem to figure out why the second one is not opening. Any ideas? Thanks!

#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;

int main( int argc, char *argv[] )
{
  // convert the C-style command line parameter to a C++-style string,
  // so that we can do concatenation on it
  assert( argc == 3 );
  const string code = argv[1];
  const string encode = argv[2];
  string firstTextFile = code;
  string secondTextFile = encode;

  //manipulate the first infile
  ifstream firstFile( firstTextFile.c_str(), ios::in );
  if( !firstFile ) 
  {
    cerr << "Cannot open text file for input" << endl;
    return 1;
  }

  string lineIn;
  string codeSubstring;
  string hexSubstring;
  while( getline( firstFile, lineIn ) ) 
  {
    hexSubstring = lineIn.substr(0, 2);
    codeSubstring = lineIn.substr(4, lineIn.length() );
    cout << hexSubstring << ", " << codeSubstring << endl;
  }

  //manipulate the second infile
  ifstream secondFile( secondTextFile.c_str(), ios::in );
  if( !secondFile ) 
  {
    cerr << "Cannot open text file for input" << endl;
    return 1;
  }

  char characterIn;
  while( secondFile.get( characterIn ) )
  {
    cout << characterIn << endl;
  }


  return 0;
}

One thing you might want to try is adding the close() call as is standard procedure after you're done using files. Sometimes issues arise with re-opening files if they were not closed properly in a previous run.

firstFile.close();
secondFile.close();

Also, you may try restarting the computer if there is some lingering file handle that hasn't been released.

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