My problem is the following:
- a
const char*
is provided to the function in which I would like to perform the operation I am going to describe - what is provided is a filename (full absolute path included) of indeterminate length
- I would like to locate the occurrence of the substring
output
and replace it withinput
- the output of these operations must be another
const char*
(too much code to change to replace it with astd::string
)
What I was thinking to do is the following
string name(filename); //filename is the "const char*" provided by the caller of the function
string portion("output");
name.replace(name.find(insert),insert.length(),"input");
const char* newfilena开发者_运维技巧me = (char*)name.c_str();
Now, my questions:
- would do this work?
- is there a better way to obtain what I need?
Thanks to anyone that will help.
Federico
This will work, but you don't need the cast on name.c_str()
(in fact, it's wrong: c_str()
returns a const char *
).
But the pointer you get from name.c_str()
is invalidated as soon as you modify name
, or when name
goes out of scope. So don't try returning newfilename
from a function, for instance.
If you need it to persist, you have no option but to dynamically allocate memory. Standard practice would be to use a smart pointer to automatically manage deallocation.const char *, you have no option but to manage this yourself. So you could do:
char *newfilename = new char[name.length() + 1];
strcpy(newfilename, name.c_str());
return newfilename;
...
delete [] newfilename;
* Well, standard practice would be to use a
std::string
! It only gets tricky if you need to interface with a legacy C API.
精彩评论