C++ 为什么我的示例程序不能创建输出文件?

标签 c++ filestream

我正在编写一个小型/beta 测试程序,它将用于我的一个更大的项目程序。它请求用户输入文件名 (IE data.txt) 并创建一个名为 filename.out (IE data.out) 的输出文件。我试过一个简单的 outFile << "text here";尝试一下,但它不会创建输出文件。我确定我在这里搞砸了一些简单的事情,但我不知道是什么。

#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();
}

最佳答案

因为您正试图打开文件进行阅读:

outFile.open(outputFile.c_str(), ios::in);

改用 ios::out

关于C++ 为什么我的示例程序不能创建输出文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696379/

相关文章:

c++ - C++ Primer 5 ed.1.23从文件流读取

c++ - 默认情况下,gcc 是否将程序链接到静态库或动态库?

c++ - 了解 C 中的基数排序

c++ - 什么影响了我的指针集的排序(具体示例)

c++ - 错误: … was not declared in this scope

C++ 使用 ldap.h 中的 ldap_bind

c++ - 将 0 打印到文件是否安全?

c# - 需要一个异步文件读取器而不知道大小

java - 从文件中读取特殊字符时出现问题

sql-server-2008 - SQL Server 2008 FILESTREAM 进度指示器