fstream没有将任何内容写入文件。

4

我试图将一些内容写入文本文件,但它甚至无法创建该文件。如果你能帮忙解决这个问题,我将不胜感激。谢谢。

#include <fstream>
#include <iostream>

int main(){
    std::ofstream file;
    file.open("path/to/file");

    //write something to file
    file << "test";

    //printing to screen
    std::cout << file.rdbuf();  

    //closing file
    file.close(); 

    return 0;
}

1
你首先要检查 salesFile.open("C:\\Users\\Tebsan\\Desktop\\Coding\\c++\\re\\salesFile.txt"); 的结果,例如使用 if(salesFile) - πάντα ῥεῖ
我尝试了这个:if (salesFile.is_open()){ salesFile << "Month: " << month << " " << year << "\n"; salesFile << "--------------------" << "\n"; . . . } else { std::cout << "Error opening file"; }但它没有显示任何错误,问题仍然存在... - Tebsan
3个回答

4
以下这行代码是罪魁祸首:
std::cout << file.rdbuf();

您不能使用rdbuf输出仅用于写入操作的文件。

删除该行,您的文件将被正确地编写。


如果您想在完成写入操作后读取文件:

解决方案1: 使用fstream打开file以进行读写操作:

std::fstream file("path/to/file", std::ios::in | std::ios::out);
// ... write to file

file.seekg(0); // set read position to beginning of file
std::cout << file.rdbuf();

解决方案2:创建一个新的std::ifstream来从文件中读取:

 // ... write to file
 file.close(); // call `close` to make sure all input is written to file

 std::ifstream inputFile("path/to/file");
 std::cout << inputFile.rdbuf();

0

感谢您的帮助!!! 我从中学到了新的东西。有趣的是,问题竟然是文件名,显然文件名太长了,对于包含文件流的新文件,我只是在名称末尾添加了“stream”,所以编译器一直运行第一个没有文件流的文件...


0
salesFile.open("C:\\Users\\Tebsan\\Desktop\\Coding\\c++\\re\\salesFile.txt"); // ...try to open existing file
    if( !salesFile.is_open() ) // ...else, create new file...
        salesFile.open("C:\\Users\\Tebsan\\Desktop\\Coding\\c++\\re\\salesFile.txt", ios_base::in | ios_base::out | ios_base::trunc);

你必须使用明确的openmode参数调用fstream::open函数

ios_base::in | ios_base::out | ios_base::trunc

否则,由于ENOENT,打开将失败。

我刚试了一下,但文件仍未被创建。奇怪的是,当我执行程序时,控制台会打印带有<iomanip>属性的内容,我已经注释掉了所有这部分的内容,以便我知道文件是否被创建... - Tebsan
2
@war1oc 这是一个 ofstream(参见 fstream),因此它将自动以 ios::out 模式打开。 - emlai
抱歉,我的错误。我刚刚运行了你的代码,奇怪的是它可以工作并且文件已经被创建了。你是否正确检查了路径?如果你使用“std::cout << file.rdbuf();”很多垃圾(“Í”)将会与通过代码编写的内容一起打印到文件中。如果我不能提供太多帮助,我很抱歉。 - war1oc
嗯,对我来说它没有打印任何垃圾,也许在某个地方加上flushclose可以防止这种情况发生? - emlai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接