开发者

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.


  1. 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.

  2. 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());
    
  3. It's int main(), even if some compilers allow void.

  4. I have strong objections to using directives. But these objections are not as widely shared as the other opinions listed in this answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜