ofstream not creating file (Node.js addon) - c++

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.

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

Related

Downloading my programs data from a webserver (Its basically just a .exe turned into .txt) but when I put it into a .exe it does not run?

So currently I am using a basic Http request to pull the exe data from my server weblink.com/Program.exe
it returns my program in .txt form but when I put it into a file it will not run.
I assume this is because I need metadata but have no clue how to find that process or even how to google something as specific as that... So I am either asking for a solution (how to add proper .exe metadata) or if there is a better way to download files like that in C++
*Note I cannot use basic windows functions such as DownloadToFileA or External Library's (Like LibCurl/Curl)
OutFile.open(XorStr("C:\\Users\\Program.exe").c_str(), std::ios::out);
if (OutFile.is_open())
{
OutFile << Output;
//Initialize .exe Meta Data???
}
OutFile.close();
You need to open your file in binary mode otherwise newline translation will screw up your executable:
OutFile.open(XorStr("C:\\Users\\Program.exe").c_str(), std::ios::out | std::ios::binary);

YAML::LoadFile(std::string const&) does not find file [yaml-cpp in ROS]

I'm trying to use data from a yaml file in a ROS(kinetic)/ c++ code so yaml-cpp seems like a good option for me. My code yields no errors but does not work properly:
It seems like the YAML::LoadFile function is not able to find my file since the following lines go to exception:
YAML::Node yamlnode_;
try{
yamlnode_= YAML::LoadFile("../yaml_file.yaml");
}
catch(std::exception &e){
ROS_ERROR("Failed to load yaml file");
}
Including yaml-cpp via
#include <yaml-cpp/yaml.h>
seems to work since YAML:: functions are recognized afterwards.
The path ../yaml_file.yaml is set up correctly which I also checked in program via
#include "../yaml_file.yaml"
which yields parsing errors (as expected) which show me that the correct file was found (but obviously cannot be included).
The yaml_file.yaml is used successfully in multiple .xacro files.
Keep in mind that I am somewhat new to ROS and yaml-cpp; I'm looking forward to see your questions and answers
That including the YAML file using #include "../yaml_file.yaml" throws errors only indicates that that file resides somewhere in the parent directory of either the current directory or one of the directories in the include path the compiler uses.
When you use "../yaml_file.yaml", for loading, then the file needs to be in the parent directory of the current directory at that point of execution. That is normally the parent directory of the directory from which you launch the program (which doesn't have to be the directory in which your program resides). But if your program changes the current directory (using chdir()), and you have no idea where it might "be", you can just want to print the result of getcwd() to get your bearings.
You should use #include <unistd.h> for getcwd() , and it takes a pointer to a character buffer large enough to hold the path and as second parameter the (size_t) that buffer can hold. (With some implementations, you can pass NULL, and a buffer that is large enough is allocated, in that case use the return value)

How to open file with ofstream so that other users can append/write to same file?

We have a binary which creates a daily CSV report with some file name like Sample_20170523 i.e filename appended with current date but now the issue is when some other runs the binary on the same day then there is error unable to open the file.Code snippet for this issue is as follows:
std::ofstream of;
of.open("FileName_20170523",ios::out);
if(!of)
std::cout<<"Unable to open file..."<<std::endl;
So after checking it seems this problem arises because the file was already created by another user. So just wanted to know is there any mechanism in c++ in which we can give 777 permissions to programmatically created file ?
You can use either chmod() or fchmod() to change the permission of a file.
system() allows to execute system commands.
system("chmod 777 diretory_to_file/name");
gives r+w+x to everyone if it already exits
std::ofstream of;
of.open("FileName_20170523",ios::out);

How to open/spawn a file with glib/gtkmm in Windows

I've already tried:
GError *pError = NULL;
string uri = g_filename_to_uri(file.c_str(), NULL, &pError);
if (!g_app_info_launch_default_for_uri(uri.c_str(), NULL, &pError)) {
cout << "Failed to open uri: " << pError->message;
}
Here I get the error "URIs not supported". Is the uri I create here wrong?
My second approach was to spawn the file with an asynchronous command line:
file = quoteStr(file);
try {
Glib::spawn_command_line_async(file);
} catch (Glib::SpawnError error) {
cout << error.what();
} catch (Glib::ShellError error) {
cout << error.what();
}
Here the Glib::SpawnError exception is thrown with the error: "Failed to execute helper program (Invalid argument)". I mean, when I execute the quoted absolute file path in the Windows cmd, it opens the file (in this case a pdf file). Does this function work different?
Hopefully this is related and can provide a real answer rather than just a (clever!) workaround.
I ran into a strange situation: Launching a file (specifically an HTML document) by g_app_info_launch_default_for_uri() or gtk_show_uri_on_window() worked when the executable was run from my build directory. However, it did not work if I copied the exe to another directory (for distribution) and ran it from there.
In the latter case, I got the same error as your 2nd quote:
Failed to execute helper program (Invalid argument)
The build directory is not in my path, and nor is it special for any other reason (it's in a temp RAM drive). So I was completely baffled.
I then thought about that error... What helper program could it possibly be talking about?
And why might that program be found when running from the build directory? Well, my build uses a libtool wrapper, and that puts a bunch of things in the path, so that we don't need to copy all the DLLs etc in just to test builds.
So, I went to investigate whether there was anything relevant-looking in paths that might be searched by the MSYS2 shell and its libtool wrapper. The prime suspect, of course, is C:\msys64\mingw64\bin. And look what I found there:
gspawn-win64-helper-console.exe
After copying this executable to the directory from which my application is launched, my program now successfully launches the URI, regardless of which folder its executable currently resides in.
Edit
After updating my packages in MSYS2, it was back to the same error - as it seems now this is the helper that is required:
gspawn-win64-helper.exe
That actually makes more sense, since my application is graphical, not console. I guess maybe something changed here recently. You could distribute both to be extra safe.
I had a similar problem and I had to give up using glib to do that and ended up implementing a simple crossplatform (win, mac and linux) compatible way to do it:
// open an URI, different for each operating system
void
openuri(const char *url)
{
#ifdef WIN32
ShellExecute(GetActiveWindow(),
"open", url, NULL, NULL, SW_SHOWNORMAL);
#elif defined(__APPLE__)
char buffer[512];
::snprintf(buffer, sizeof(buffer), "open %s", url);
::system(buffer);
#else
char buffer[512];
::snprintf(buffer, sizeof(buffer), "xdg-open %s", url);
::system(buffer);
#endif
}
... it's not very nice but it's small and it works :)

C++ - Can't open file from network path in Windows

I'm having problems using native C++ to open a file located on a network drive on a Windows box. My code works fine if the file is local, but fails if the file is on a network share. I can read the file from Windows explorer perfectly fine.
ifstream ifs(cFilename);
if(ifs.is_open())
{
// Read file here. (This never works for a network path)
}
I've also tried this:
struct stat sb;
if (stat(cFilename, &sb) == 0)
{
// Read file here. (This never works for a network path)
}
My path is formatted correctly (e.g. "\\server\filename.ext"), but I still can't open it. Any ideas?
If the name is in the form \\server\filename, then it seems that might not be correct. I believe that typically it needs a share name as well:
\\server\share\filename
Also, make sure that in the code, you escape the backslashes (e.g., \\\\server\\share\\filename).