【问题标题】:windows, c++: send file to exe (c++ solution) and read data from sent filewindows、c++:发送文件到exe(c++解决方案)并从发送的文件中读取数据
【发布时间】:2016-07-12 18:22:20
【问题描述】:

我的目标是将任意文本文件发送到一个 exe,它是一个 c++ 项目的构建。在 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{用户}\AppData\Roaming\Microsoft\Windows\SendTo

问题:

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

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

ifstream readFile(argv[1]); 

非常感谢!

大卫

【问题讨论】:

  • SendTo 已经做到了这一点。你测试过有什么问题吗?
  • 我没有测试它,因为 argv[1] 对我来说太奇怪了。正如“Remy Lebeau”所解释的那样,我必须进行一些字符串处理才能获得源文件的可解释路径。所以,ifstream readFile(argv[1]); 正是我想要的。接下来是了解其内容并进行一些字符串处理。谢谢。

标签: c++ file path sendto


【解决方案1】:

无论您使用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";
  }
}

【讨论】:

  • 是的,你是对的。有用!如何将 output.txt 写入读取 input.txt 的同一目录?我的情况是输出目录是exe所在的位置。我试图打印 argv[1] 但它似乎是一个标识符,而不是源文件的完整路径 (c:\foo\input.txt)。
  • 再次检查。 argv[] 值将包含输入文件的完整 路径和文件名。您必须编写代码来解析值以从文件名中拆分路径,然后您可以将所需的输出文件名附加到提取的路径中。这是处理 101 种东西的基本字符串,你应该能够搜索并找到大量的教程/示例来帮助你。如果您仍然无法弄清楚,请发布一个新问题。此问题已按要求回答。
  • 或者直接使用boost::filesystem::path::parent_path
  • 好的,会试试的。非常感谢!
猜你喜欢
  • 2022-10-06
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
相关资源
最近更新 更多