【问题标题】:I cannot create a file in C++ using fstream我无法使用 fstream 在 C++ 中创建文件
【发布时间】:2020-09-02 21:08:02
【问题描述】:

这是我关于堆栈溢出的第一个问题,如果我搞砸了,请原谅我(笑) 编码语言:C++ IDE:代码::块 编译器:GNU GCC 操作系统:Windows

让我澄清一下: 这是我的代码:

#include <iostream>
#include <fstream>
int main() {
   std::fstream fileObject;
   std::string line;
   fileObject.open("randomFile.txt");

   fileObject << "Random text\n kjshjdfgxhkjlwkdgxsdegysh";
   while (getline(fileObject, line)   ) {
       std::cout << line << "\n";
   }
   fileObject.close();
}

这不会产生任何错误,但是当我检查我的项目文件时,文件 randomFile 不存在,控制台屏幕上也没有出现任何文本。 但是,这段代码确实有效:

#include <iostream>
#include <fstream>
int main() {
    std::ofstream fileObject;
    fileObject.open("randomFile.txt");
    fileObject << "Random text\n kjshjdfgxhkjlwkdgxsdegysh";
    fileObject.close();
} 

它创建文件并插入指定的文本... 我还有一个次要问题:如果我尝试创建一个同名的 ifstream 和 ofstream 对象,它会显示为一个错误,但我不知道如何制作它,以便我可以写入文件并从中读取它使用相同的代码...

【问题讨论】:

  • 您是否检查了该文件是否出现在Debug 文件夹中(或创建.exe 的位置)?
  • 你怎么知道没有错误?没有错误检查。各种各样的坏蓝精灵都可能发生,如果你不检查,你就不会知道。
  • 我不确定你所说的终止输入是什么意思...
  • @fartgeek 这很可能不是问题所在,你close() 还是文件。
  • 我确实检查了创建.exe的文件夹,那里什么都没有

标签: c++ file fstream


【解决方案1】:

你需要阅读文档,你不能通过猜测来编程 C++。这些选项允许您打开文件以同时读取和写入,但有以下注意事项

// error if the file does not exist
std::fstream fileObject("randomFile.txt");

或(相同的东西)

// error if the file does not exist
std::fstream fileObject("randomFile.txt", 
    std::ios_base::in|std::ios_base::out);

或

// destroys contents if the file exists, but creates file if it does not
std::fstream fileObject("randomFile.txt", 
    std::ios_base::in|std::ios_base::out|std::ios_base::trunc);

如果这些选项都不是您想要的,那么您将不得不在打开文件之前检查文件是否存在。

参考here。

【讨论】:

  • 谢谢!这就是我需要的。我不知道你不能用 std::fstream 创建文件...
  • @fartgeek - 很可能使用std::fstream 创建文件。这个答案的重点是,默认情况下,尝试打开不存在的文件将导致错误,而不是创建文件。您以默认方式打开了fstream,因此打开不存在的文件会产生错误。如果您想使用fstream 创建文件,则必须提供第二个参数的适当值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
相关资源
最近更新 更多