Why does this program not generate error when the output is not created?

Here is the simple program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using namespace std;

#include <fstream>
#include <iostream>

using namespace std;

int main(void)
{
	std::ofstream myfile;
	const char path[] = ".\\output_file\\output\\";
	const char fname[] = "my_output.txt";
	const char data[] = "ABCDEFGHIJ";

	char* full_path = nullptr;
	full_path = new char[sizeof(path)+sizeof(fname)];
	strcpy(full_path, path);
	strcat(full_path, fname);

	myfile.open(full_path, std::ios::out | std::ios::trunc);
	myfile.write(data, strlen(data));
	myfile.close();
	delete full_path;
	return 0;
}


Is there a better way to concatenate the path and fname to get full path?

Anyway, the question is that the folder "output_file" does not exist and thus the sub-folder "output" also does not exist. Yet, the program ends without generating any error or throwing an exception. Why?

If I change the path to ".\\", then it works and creates the file. However, I would expect that when I call the open file function using non-existance directory, it should complain as no output is created and nothing is written.
Last edited on
Have a look at:
http://www.cplusplus.com/reference/fstream/ofstream/open/
It says an exception may be thrown, but you are not trying to catch it. Did your program return 0 when it was done (and was not able to find the folder)?

In addition, when you open a file, it is a good habit to check if you were successful. Even if a file exists, it may for example be read-only. Have a look here:
http://www.cplusplus.com/reference/fstream/ofstream/is_open/
Last edited on
yes, it is exiting with return code 0

However, using the is_open() that you mentioned returns correct result. Therefore, it seems that exception is not being thrown.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>
#include <iostream>
#include <string>

int main()
{
    const std::string path_to_dir = "./output_file/output/";
    const std::string fname = "my_output.txt";
    const std::string full_path =  path_to_dir + fname ;
    const char data[] = "ABCDEFGHIJ";

    std::ofstream myfile(full_path) ; // constructor opens file for output

    if( !myfile.is_open() ) std::cerr << "could not open file '" << full_path << "' for output.\n" ;
    else if( myfile << data ) std::cout << "data was written to file.\n" ;
    else std::cout << "write failed.\n" ;
}
Topic archived. No new replies allowed.