【问题标题】:Open a file in c++ using environment variables使用环境变量在 C++ 中打开文件
【发布时间】:2014-09-11 03:31:28
【问题描述】:

我正在尝试创建一个程序来使用环境变量中的值打开文件..

我的代码:

#include<iostream>
#include<cstdlib>
#include<sstream>
#include<cstring>
using namespace std;
void main(int argc, char *argv[])
{
std::stringstream stream;
int a;
cout<<"Press 1 to open Remainder: "<<endl;
cout<<"Press any other key to exit: "<<endl;
cin>>a;
if(a==1)
{
    system("\"C:\\Documents and Settings\\%USERNAME%\\My Documents\\CorelDRAW X3.txt\"");
//  system(stream.str().c_str());
}
else
{
    exit(0);
}
}

这是输出:

Press 1 to open Remainder:
Press any other key to exit:
1
'C:\Documents' is not recognized as an internal or external command,
operable program or batch file.
Press any key to continue . . .

但是当我输入我的用户名时,它会完美运行..

我想在另一台电脑上使用这个程序,所以我使用了环境变量

有什么帮助吗?

谢谢。

【问题讨论】:

  • 使用批处理文件会更容易。正如在一些答案中已经指出的那样,解决问题的一种方法是引用路径。另一种方法是使用短名称。在命令解释器中找到当前目录的短路径的一种方法是for /d %d in (.) do @echo %~fsd

标签: c++ environment-variables


【解决方案1】:

您应该避免使用system (),但如果您愿意,可以使用GetUserName 函数获取用户名,并将其放入字符串中。

【讨论】:

    【解决方案2】:

    您的问题是(错误)使用 system 函数调用来打开文本文件。它不处理文件名中的空格,因为system 使用这些空格将程序与其参数分开。虽然这可以通过将程序(或在您的情况下是文本文件)名称放在一组额外的引号中来解决,但这并不是真正的正确解决方案。

    尝试使用 ShellExecute 代替 Windows API - this answer. 中有一个很好的示例

    【讨论】:

      【解决方案3】:

      您需要一组额外的引号。像这样使用它。

      system("\"\"C:\\Documents and Settings\\%USERNAME%\\My Documents\\CorelDRAW X3.txt\"\"");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-31
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 2018-09-12
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多