Reputation: 123
I have a c++ program that I associated with .bin files, so that whenever the .bin file is opened, it is opened with myProgram.exe.
How do I get the filename of the associated file that opened my program?
Upvotes: 1
Views: 2719
Reputation: 145429
In plain C++ you can use the arguments of main
:
#include <iostream>
int main( int argc, char* argv[] )
{
using namespace std;
cout << argc << " arguments:" << endl;
for( int i = 0; i < argc; ++i )
{
cout << "[" << argv[i] << "]" << endl;
}
}
But there is a problem with that, namely that C and C++ main
was designed for *nix, not Windows. The Holy C++ Standard recommends that the runtime should supply the main
arguments UTF-8-encoded, but alas, that does not happen with conventional Windows C++ compilers. So in Windows this method might not work for filenames with e.g. Norwegian, Greek or Russian characters.
In Windows, for a program intended to be used by others you can instead use the (Unicode version of the) Windows API function GetCommandLine
, and its parser cousin CommandLineToArgvW
in order to split the command line into individual arguments.
Alternatively, with Microsoft's implementations of the C and C++ languages you can use the non-standard startup function wmain
. I don't recommend that, however. I think it is a good idea to keep to the international standards for C and C++ as much as practically possible, and there is certainly no pressing reason to use wmain
, even though it can be convenient for small toy programs.
Cheers & hth.,
Upvotes: 1
Reputation: 898
IIRC, it will be the second command line parameter passed into your application. The first parameter will the name of your actual program (executable).
Upvotes: 1
Reputation: 308520
The process of opening a file via its extension is controlled by a set of entries in the system registry. One of the final steps specifies the command that should be executed, and usually the file name is included in the command. Check your command line parameters to see if the file name is given.
The process is described here: http://msdn.microsoft.com/en-us/library/cc144175(v=vs.85).aspx
Upvotes: 1