[英]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 ()
,但是如果愿意,可以使用GetUserName
函数获取用户名,并将其放入字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.