arthurakay arthurakay - 2 months ago 8
C++ Question

ofstream not creating file (Node.js addon)

I am attempting to create an addon for Node.js that (among other things) writes content to a file inside my C++ class using

ofstream
.

std::ofstream license_file;

std::string fileContent(*NanAsciiString(args[0]));

license_file.open(PATH);

//file doesn't yet exist, so create it
if(!license_file) {
printf("ERROR: %s (%s)\n", strerror(errno), PATH);
}

license_file << fileContent;
license_file.close();


This works fine if
PATH
is set to the same directory as my Node.js code (e.g.
./license.txt
).

However,
ofstream
fails to open/create the file in question if it is located anywhere else. For example, using
~/license.txt
does not work (note: I'm running OSX).


The error reported is always
No such file or directory
-- even after I physically create
~/license.txt
.

Any ideas why this works in one directory but not others? If it were a permissions issue I would expect a different error message.

For the record, I've seen about 20 other SO questions about "ofstream fails to create file" but passing additional flags into
open()
has no effect. I have a feeling this is somehow related to running inside Node/V8.

Answer

I think the issue is that you need to find out the user directory in a different way than using ~.