Can you tell me why the files I'm loading in the code below will not load without their full file paths? The files are in the same directory as the executable.
I would like to eventually replace the filename with a user variable, so I can't include the paths in the final version.
I'm using Xcode, and oddly enough the program works fine without paths within Xcode, but when I try running the executable directly from finder, I get a file load error ("Unable to open airship.syx\n" defined in the code below).
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
int main () {
char buffer[128]={0};
long size;
// using the direct filenames didn't work; I had to include the paths as well.
// ifstream infile ("airship.syx", ios::binary);
// ofstream outfile ("copy.syx", ios::binary);
ifstream infile ("/Users/mbuchanan/Documents/opensysex/build/Debug/airship.syx", ios::binary);
ofstream outfile ("/Users/mbuchanan/Documents/opensysex/build/Debug/copy.syx", ios::binary);
if (!infile)
{
cout << "Unable to open airship.syx\n";
return EXIT_FAILURE;
}
//get size of file
infile.seekg (0, ifstream::end);
size = infile.tellg();
infile.seekg(0);
//read content of infile
infile.read (buffer, size);
//write to outfile
outfile.write (buffer, size);
//close files
outfile.close();
infile.close();
return 0;
}
If you specify a relative file name, it is relative to the current working directory. Which one that is depends on how the program was started.
It doesn't have anything to do with C++, in any case.
So the current working directory is not guaranteed to be the directory that the program is run from?
Correct.
For example, At the command line, it is wherever you are then time. So if you start an executable in a different directory it won't be the exe's directory.
This little bit of code doesn't look quite right to me
arg[0] is generally the path. I would have thought you need to get the app path (arg[0]), remove the file spec, and then append the filename (arg[1]) to it. Handling multiple files would involve more work. (I'm not sure I understand the command line: does it take a file name?)
I am not sure how Mac works, but I do know that the Linux and Windows command lines behave differently depending on how the app was launched. So it sometimes turns up as a full path, and sometimes a relative path. So I convert to to always be a full path with either _fullpath() or realpath() -- the latter should work for OS X.
(where maxPath is defined to _MAX_PATH or PATH_MAX -- not 100% sure about the latter)