2014-02-07 39 views
0
#include <iostream> 
#include <windows.h> 
#include <Lmcons.h> 
#include <fstream> 
using namespace std; 
main(){ 
char username[UNLEN+1]; 
DWORD username_len = UNLEN+1; 
GetUserName(username, &username_len); 
string cmd("C:\\Users\\"); 
cmd+=username; 
cmd+=("\\AppData\\Roaming\\MiniApps"); 
} 

现在我在“cmd”中有完整的路径url,并且我想将此变量用作C++文件处理中的路径。像我如何在C++中使用字符串变量作为路径url

ofstream file; 
file.open(cmd,ios::out|ios::app); 
+2

究竟是什么问题?还是这个问题? – Raxvan

+8

file.open(cmd.cstr(),ios :: app) –

+0

编译器使用.c_str()进行编译,但不会进入路径只是创建一个文件,其中保存.exe文件 – king4aol

回答

1

打开使用ofstream的文件流,写的内容并关闭。

#include<iostream> 
#include <windows.h> 
#include <Lmcons.h> 
#include <fstream> 
#include <string> 

int main(){ 
    char username[UNLEN+1]; 
    DWORD username_len = UNLEN+1; 
    GetUserName(username, &username_len); 
    std::string cmd("C:\\Users\\"); 
    cmd+=username; 
    cmd+=("\\AppData\\Roaming\\MiniApps.txt"); 
    std::ofstream file; 
    file.open (cmd.c_str(), std::ofstream::out | std::ofstream::app); 
    file << " Hello World"; 
    file.close(); 
    return 0; 
} 
1

用C++ 11,你可以做

ofstream file(cmd,ios::app); 

没有你所要做的

ofstream file(cmd.c_str(),ios::app); 
+0

编译器使用.c_str()进行编译,但不会进入路径,只需创建一个保存.exe文件的文件 - – king4aol

相关问题