使用环境变量在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
使用这些空格将程序与其参数分开。虽然这可以通过将程序(或者在您的情况下是文本文件)的名称放在一组额外的引号中来解决,但这并不是真正正确的修复方法。
尝试使用ShellExecute
来代替Windows API -在这个答案中有一个很好的例子。
您应该避免使用system ()
,但如果您愿意,您可以使用GetUserName
函数获取用户名,并将其放入字符串
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 挂起和取消挂起一个文件DLL
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何打开并写入一个名称取自C++中字符串的文件
- 构建一个由C和C++文件组成的库
- c++多进程编写一个唯一的文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 如何将class.cpp和class.hpp编译为一个.o文件
- 写入文件会产生一个空文件或根本没有文件
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 生成一个生成文件,该生成文件使用Automake在一个步骤中编译和链接所有源文件
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- Pantheios 不使用 MFC 应用程序写入一个文件(一个 exe + 两个 DLL)
- 在C++中一次读取一个文件一个int
- 输入/输出文件(一个字母的大写)
- 如何使用两个预编译的头文件.一个用于托管代码,另一个用于非托管代码.xxx.PCH不是一个有效的预编译头文件