windows,c++:将文件发送到exe(c++解决方案),并从发送的文件中读取数据

windows, c++: send file to exe (c++ solution) and read data from sent file

本文关键字:文件 c++ 读取 数据 exe windows 解决方案      更新时间:2023-10-16

我的目标是将任意文本文件发送到作为c++项目构建的exe。在c++项目中,我想读取发送到exe的文件。因此,我认为我需要将发送的文件的路径传递给应用程序(exe)。

我的c++代码[正在工作!]:

#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();
}

我的Windows配置:

在以下路径中,我创建了一个exe的快捷方式(c++项目的构建):C: \Users{User}\AppData\Roaming\Microsoft\Windows\SendTo

问题:

我想右键单击任意文本文件并将其(SendTo)传递到exe。如何将发送文件的路径作为参数传递给应用程序,以便应用程序可以读取发送的文件?

当路径作为参数传递时,我想代码行应该是这样的:

ifstream readFile(argv[1]); 

非常感谢!

David

无论使用SendTo还是OpenWith,单击的文件名将作为命令行参数传递给可执行文件。因此,argv[]数组将包含文件名(在argv[1]处,除非SendTo快捷方式指定了其他命令行参数,在这种情况下,您必须相应地调整argv[]索引)。

我刚刚用SendTo做了一个测试,argv[1]运行良好。只需确保在尝试打开文件名之前检查argc,例如:

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";
  }
}