umar_
umar_

Reputation: 491

How can I use a string variable as a path url in C++

#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");
}

Now I have complete path url in "cmd", and i want to use this variable as a path in c++ file handling . like

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

Upvotes: 0

Views: 950

Answers (2)

SridharKritha
SridharKritha

Reputation: 9631

Open a file stream using ofstream, write the content and close.

#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;
}

Upvotes: 1

TNA
TNA

Reputation: 2745

With C++11 you can do

ofstream file(cmd,ios::app);

Without you have to do

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

Upvotes: 1

Related Questions