0

When file is checked if its open, it will not open.

The file doesn't open when ran, as it says "Unable to open file" based on my test cases. Is there anyway to fix this?

Is there something I need to fix with the file io function (which I created at the bottom) or something to do inside of the if statement (checking if its open)

#include "header.hpp"
int main() {
  string infile, outfile;
  print();
  readFilenames(infile, outfile);
  ifstream fin(infile.c_str());
  // check if file can be opened
  fin.open(infile);
  if (fin.is_open())
  {
    string name, smallName = "", largeName = "";
    int id, numPeople = 0, smallId, largeId;
    double balance, totalBalance = 0, largeBalance, smallBalance;
    cout << "\n\nReading records from input file " << infile << endl;
    cout << "Output records to output file " << outfile << endl;
    ofstream fout(outfile.c_str());
    print(fout);
    fout << "List of Entries : " << endl;
    printHeading(fout);
    // read till the end of file
    while (!fin.eof())
    {
      numPeople++;
      getline(fin, name); // read name
      name = name.substr(0, name.length() - 1); // remove '\n' from the end of name
      // read id and balance
      fin >> id >> balance;
      }
  } else
    cout << "Unable to open file : " << infile << endl;
  cout << "\nThank you for using my program";
  return 0;
}

void readFilenames(string &infile, string &outfile)
{
  cout << "What input file would you like to use? ";
  getline(cin, infile);
  infile = infile.substr(0, infile.length() - 1);
  cout << "What output file would you like to use? ";
  getline(cin, outfile);
  outfile = outfile.substr(0, outfile.length() - 1);
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64
Meez
  • 1
  • 1
  • 2
    You probably put your file in the wrong place. – drescherjm Dec 12 '22 at 20:59
  • 1
    `ifstream fin(infile.c_str());` opens the input file (as would `ifstream fin(infile);`, more clearly). `fin.open(infile);` opens it again. Don't do that. – Pete Becker Dec 12 '22 at 21:00
  • 2
    `while (!fin.eof())` should be avoided: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Dec 12 '22 at 21:01
  • Opening a file twice is a guaranteed failure. – Sam Varshavchik Dec 12 '22 at 21:03
  • `infile = infile.substr(0, infile.length() - 1);` Why are you doing this? – drescherjm Dec 12 '22 at 21:04
  • 1
    `infile = infile.substr(0, infile.length() - 1);` removes the last character from the input string. Absent unusual requirements, there’s no need to do this. `std::getline` does not copy the delimiter into the destination string. – Pete Becker Dec 12 '22 at 21:28

0 Answers0