I wrote a c++ program that can save its internal state to the disk in a file of a custom type. How can I get windows to run my program upon a file of this type being double clicked? Is there a method of passing arguments to main() so the program knows what file was selected?
Asked
Active
Viewed 285 times
-1
-
This should be moved to SuperUser I believe? It's a question about Windows default programs, not programming. – Yksisarvinen Apr 20 '18 at 07:52
-
2This [SO article](https://stackoverflow.com/questions/9093481/add-a-new-file-association-in-windows-7?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) might help – Jabberwocky Apr 20 '18 at 07:54
-
https://msdn.microsoft.com/en-us/library/windows/desktop/cc144175(v=vs.85).aspx – SHR Apr 20 '18 at 07:56
-
1@Yksisarvinen: It's two questions in one. The second part ("method of passing arguments to main()) is clearly about programming. – Andreas H. Apr 20 '18 at 08:34
-
1Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the [ask] page for help clarifying this question. – zett42 Apr 20 '18 at 10:50
-
Thank you all for the feedback! – Connor Carr Apr 21 '18 at 00:49
1 Answers
1
If you use "Run with..." from the Windows explorer context menu, you can select your application binary.
Windows will supply the absolute file path as the first argument to your application.
int main(int argc, char **argv)
{
if (argc < 2)
std::cout << "No argument" << std::endl;
else
std::cout << "Filename is " << argv[1] << std::endl;
}
Why 2 arguments? Because arguments always start in argv[1]. argv[0] usually contains the path to your application binary.
If you call "d:\MyApp.exe c:\MyImage.bmp" then
argc == 2
argv[0] == "d:\MyApp.exe"
argv[1] == "c:\MyImage.bmp"

Andreas H.
- 1,757
- 12
- 24
-
3*"Because argv[0] always contains the path to your application binary."* - This is not true. Passing the pathname to the executable image as the first command line argument is a *convention*, not a strict rule. If you read the documentation for [CreateProcess](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425.aspx), you will see, that there are no restrictions as to what you can pass as the first command line argument. – IInspectable Apr 20 '18 at 08:28