使用环境变量在c++中打开一个文件

Open a file in c++ using environment variables

本文关键字:文件 一个 环境变量 c++      更新时间:2023-10-16

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

我代码:

#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使用这些空格将程序与其参数分开。虽然这可以通过将程序(或者在您的情况下是文本文件)的名称放在一组额外的引号中来解决,但这并不是真正正确的修复方法。

尝试使用ShellExecute来代替Windows API -在这个答案中有一个很好的例子。

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