My goal is to send an arbitrary text file to a exe which is a build of a c++ project. In the c++ project I would like to read the file which was sent to the exe. Hence, I think I need to pass the path of the sent file to the application (exe).
My c++ code [is working!]:
#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
std::string readLineFromInput;
ifstream readFile("input.txt"); // This is explizit.
// What I need is a dependency of passed path.
getline(readFile, readLineFromInput);
ofstream newFile;
newFile.open("output.txt");
newFile << readLineFromInput << "\n";
newFile.close();
readFile.close();
}
My Windows configuration:
In the following path I created a shortcut to the exe (build of c++ project): C:\Users{User}\AppData\Roaming\Microsoft\Windows\SendTo
Question:
I want to right click to an arbitrary text file and pass it (SendTo) to the exe. How can I pass the path of the sent file as an argument to the application such that the application can read the sent file?
When the path is passed as an argument the line of code should be like this, I guess:
ifstream readFile(argv[1]);
Much thanks!
David
Whether you use SendTo
or OpenWith
, the clicked filename will be passed to your executable as a command-line parameter. As such, the argv[]
array will contain the filename (at argv[1]
, unless your SendTo
shortcut specifies additional command-line parameters, in which case you would have to adjust the argv[]
index accordingly).
I just did a test with SendTo
and argv[1]
works fine. Just make sure you check argc
before attempting to open the filename, eg:
int _tmain(int argc, _TCHAR* argv[])
{
if (argc > 1)
{
std::string readLineFromInput;
std::ifstream readFile(argv[1]);
if (readFile)
std::getline(readFile, readLineFromInput);
std::ofstream newFile(_T("output.txt"));
if (newFile)
newFile << readLineFromInput << "\n";
}
}