繁体   English   中英

使用环境变量在C ++中打开文件

[英]Open a file in c++ using environment variables

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

我的代码:

#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 . . .

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

我想在另一台计算机上使用此程序,所以我使用了环境变量

有什么帮助吗?

谢谢。

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

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

您的问题是(错误)使用system函数调用来打开文本文件。 它不能处理文件名中的空格,因为system使用这些空格将程序与其参数分开。 尽管可以通过将程序(或您的文本文件)名称放在另外的引号中解决此问题,但这并不是正确的解决方法。

尝试从Windows API使用ShellExecute代替- 此答案中有一个很好的例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM