fstream没有在文件中写入任何内容

fstream is not writing anything on the file

本文关键字:任何内 文件 fstream      更新时间:2023-10-16

我试图将一些内容写入文本文件,但它甚至无法创建文件。如果你能帮我做这件事,我将不胜感激。谢谢

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

下面一行是罪魁祸首:

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();
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,打开将失败。

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