简体   繁体   English

从 C、C++ 中的变量获取文件路径

[英]Taking path to file from variable in C, C++

I'm doing a little project using C, C++ and dirent.h .我正在使用 C、C++ 和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. documentLocation是我在程序开始时提供的变量,我想在其中创建一个新目录。 Adding fileName , I want to create a new directory in this folder.添加fileName ,我想在这个文件夹中创建一个新目录。 But I get an error:但我收到一个错误:

expression must have integral or enum type表达式必须具有整数或枚举类型

You can't use + to concatenate C strings.您不能使用+连接 C 字符串。 Concatenate the std::string s first, then get the C string from that.首先连接std::string s,然后从中获取 C 字符串。

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

c_str() returns a const char * , so in c_str()返回一个const char * ,所以在

documentLocation.c_str()+fileName.c_str()

You try to add two const char * , which does not work.您尝试添加两个const char * ,这不起作用。

std::string overloads the + operator: std::string重载+运算符:

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

First add (concatenate) the two strings, then take the c_str() of the result.首先将两个字符串相加(连接),然后取结果的c_str()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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