Reputation: 379
I'm writing a small/beta testing program that will be put to use in my much bigger program for a project. It requests the user for an input file name (IE data.txt) and creates an output file named filename.out (IE data.out). I've tried a simple outFile << "text here"; to try it out but it doesn't create output file. I'm sure I'm messing something simple here but I can't figure out what.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//Global variables
ifstream inFile;
ofstream outFile;
void main()
{
// Requests user for input filename
string inputFile;
cout << "Enter File Name: ";
cin >> inputFile;
string outputFile = inputFile.substr(0, inputFile.find_last_of('.')) + ".out";
// Opens both inputFile and outputFile
inFile.open(inputFile.c_str(), ios::in);
outFile.open(outputFile.c_str(), ios::in);
// Checks for input file
if (!inFile)
{
cout << "Unable to open file" << endl;
exit(1);
}
outFile << "Hello world!";
inFile.close();
outFile.close();
}
Upvotes: 2
Views: 3618
Reputation: 224079
Why did you make these streams global variables rather than local ones? In C++, it's generally preferred to construct objects as late as possible. If you do this, you have all information available to open the streams right in the constructor, which can take the same arguments as the open()
member function.
One difference between std::ifstream
and std::ofstream
is that their open()
member functions and constructors apply a different default opening mode. It's in
for std::ifstream
and out
for std::ofstream
. You can always override these, but that would somewhat defeat the reason for using those streams in the first place. You could use std::fstream
, too. For that you would always have to supply the opening modes. If you're using std::ifstream
and std::ofstream
, just skip the opening modes. Here's how this is looks when using the constructors instead of the open()
member functions (it looks pretty much the same with the latter):
std::ifstream inFile(inputFile.c_str());
std::ofstream outFile(outputFile.c_str());
It's int main()
, even if some compilers allow void
.
I have strong objections to using directives. But these objections are not as widely shared as the other opinions listed in this answer.
Upvotes: 3
Reputation: 70158
Because you're trying to open the file for reading:
outFile.open(outputFile.c_str(), ios::in);
Use ios::out
instead.
Upvotes: 9