A
A
al3x3y772020-08-01 20:06:26
C++ / C#
al3x3y77, 2020-08-01 20:06:26

How to create a folder given username c++?

How to create a folder on the desktop if the username is not known?
The usual way works

CreateDirectory("C:\\Users\\Username\\Desktop\\Dir",NULL);

And if you try to put the username from a variable, it gives an error
string username = getenv("username");	
CreateDirectory(L"C:\\Users\\"+username+"\\Desktop\\Dir",NULL);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AnT, 2020-08-01
@al3x3y77

And why did you even decide that the folder Usersis located on C:?
You should create folders in the user's home directory through the value of the environment variable %USERPROFILE%, and not manually glue the pieces together, as in your example. %USERPROFILE%Contains the full path to the current user's home directory . From there, start dancing.
And trying to concatenate through +wide string literals and a narrow std::stringone is useless. Why are you mixing wide and narrow lines in your code? If you want to work with wide lines, work with wide lines. std::wstring, not std::string.

E
Egorithm, 2020-08-05
@EgoRusMarch

So you use std::wstringfor username. And instead of escaping, you can either use raw strings LR"(path\to\file)", or just write a forward slash, not a backslash L"path/to/file". And as already noted, use the STL Filesystem . The home directory is best taken from the environment variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question