Code won't make text file?

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)


1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>


int main()
{
	std::fstream file;
	file.open("hello.txt");
	file << "hi";
	file.close();
	return 0;
}


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.
Last edited on
> Doesn't the quotations tell the compiler to make the text file at the location of the executable?

The file would be in the current working directory.

Try running this (Visual Studio):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <filesystem>
#include <string>

int main()
{
    const std::string file_name = "hello.txt";

    {
        std::ofstream file(file_name);
        if( file.is_open() )
        {
            std::cout << "file is opened\n";
            file << "hi\n";
        }
        else std::cout << "failed to open file\n";
    }

    namespace fs = std::experimental::filesystem;
    std::cout << "current directory: " << fs::current_path() << '\n'
              << "full path to file: " << fs::absolute(file_name) << '\n'
              << "        file size: " << fs::file_size(file_name) << " bytes\n" ;
}
Topic archived. No new replies allowed.