Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fstream is not writing anything on the file

Tags:

c++

fstream

I'm trying to write some things to a text file but it won't even create the file. I will appreciate a lot if you can help me with this. Thanks.

#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;
}
like image 688
Tebsan Avatar asked Oct 23 '25 01:10

Tebsan


1 Answers

The following line is your culprit:

std::cout << file.rdbuf();

You cannot use rdbuf to output a file that was opened for write operations only.

Remove that line and your file will be written correctly.


If you want to read your file after you've finished writing to it:

Solution 1: Open file for both read and write operations using fstream:

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

Solution 2: Create a new std::ifstream to read from file:

 // ... 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();
like image 188
emlai Avatar answered Oct 25 '25 16:10

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!