Why is my output file empty in this simple program using std::fstream?

DEdesigns57 picture DEdesigns57 · Sep 30, 2011 · Viewed 14.4k times · Source

I am trying to understand how to read information form an input file and write that data into an output file. I understand how to read from a file and dispaly its contents, but I DONT understand how to write to a file or display its contents. My program runs fine but when I check my output txt file, there is nothing in it! What could I be doing wrong? input file contains 3.1415 2.718 1.414.

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

int main()
{
float fValue;
fstream inputFile;
ofstream outputFile;

inputFile.open("C:\\Users\\David\\Desktop\\inputFile.txt");
outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");

cout << fixed << showpoint;
cout << setprecision(3);
cout << "Items in input-file:\t " << "Items in out-put File: " << endl;

inputFile >> fValue;    // gets the fiest value from the input

while (inputFile) // single loop that reads(from inputfile) and writes(to outputfile)    each number at a time.
{
    cout << fValue << endl; // simply prints the numbers for checking.
    outputFile << fValue << ", "; // writes to the output as it reads numbers from the input.
    inputFile >> fValue; // checks next input value in the file
}



outputFile.close();
inputFile.close();


int pause;
cin >> pause;

return 0;
}

Answer

David Nehme picture David Nehme · Sep 30, 2011

On windows, it's likely that you have the output file open with something like notepad and your C++ program is not opening the file for output. If it can't open the file, the ofstream::open function will silently fail. You need to check the status of outputFile after you attempt to open it. Something like

outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");
if (!outputFile) {
  cerr << "can't open output file" << endl;
}

If the status of outputFile is not ok, then you can do

outputfile << "foobar";

and

outputfile.flush();

till the cows come home and you still won't get any output.