简体   繁体   中英

Taking path to file from variable in C, C++

I'm doing a little project using C, C++ and dirent.h . I want to ask if its possible to take a path to a folder/file from a variable:

string fileName;
cout << "Create new file" << endl;
cin>>fileName;

CreateDirectory(documentLocation.c_str()+fileName.c_str(), NULL);

documentLocation is my variable I gave at the beginning of the program where I want to create a new directory. Adding fileName , I want to create a new directory in this folder. But I get an error:

expression must have integral or enum type

You can't use + to concatenate C strings. Concatenate the std::string s first, then get the C string from that.

CreateDirectory((documentLocation + fileName).c_str(), NULL);

c_str() returns a const char * , so in

documentLocation.c_str()+fileName.c_str()

You try to add two const char * , which does not work.

std::string overloads the + operator:

std::string path = documentLocation + fileName;
CreateDirectory(path.c_str(), NULL);

First add (concatenate) the two strings, then take the c_str() of the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM