C++ Why won't my sample program create the output file?
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>
#in开发者_运维百科clude <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();
}
Because you're trying to open the file for reading:
outFile.open(outputFile.c_str(), ios::in);
Use ios::out
instead.
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
andstd::ofstream
is that theiropen()
member functions and constructors apply a different default opening mode. It'sin
forstd::ifstream
andout
forstd::ofstream
. You can always override these, but that would somewhat defeat the reason for using those streams in the first place. You could usestd::fstream
, too. For that you would always have to supply the opening modes. If you're usingstd::ifstream
andstd::ofstream
, just skip the opening modes. Here's how this is looks when using the constructors instead of theopen()
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 allowvoid
.I have strong objections to using directives. But these objections are not as widely shared as the other opinions listed in this answer.
精彩评论