A while back I got into file stuff in C++ and it was working fine, like I've made small programs with it, but now my code won't work! (This is new code that I hadn't written before, but it's extremely simple)
It compiles but won't make the text file! Doesn't the quotations tell the compiler to make the text file at the location of the executable? Why is it not being made at all?
Thank you, I'm very comfused. I tried running this in codeblocks but its saying I'm missing some dll when I try to run, and in visual studio it runs fine but doesn't actually make the file.
You should always test if the file actually opened. For whatever reason, you have chosen to use an fstream and open it in the default mode, which is in|out. But with that mode, it is an error if the file doesn't exist. You need to add trunc to the mode to make it create a new file if one doesn't already exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
int main()
{
std::fstream f("hello.txt", f.in | f.out | f.trunc);
if (!f)
{
std::cerr << "Cannot open hello.txt\n";
return 1;
}
f << "hi\n";
// file automatically closed at end of function
// 0 automatically returned at end of main
}
However, you probably just meant to use ofstream instead of fstream:
std::ofstream f("hello.txt"); // probably what you meant to say
And I have no idea what codeblocks is complaining about, but it doesn't seem to have anything to do with this code.