2014-02-07 37 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

相關問題