How does one pass a const char *path to fts_open? I would like to pass a filePath.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.
const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr, but you can change the pointer itself.
The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).
I assume you want to know how to pass this single path to the argv
(type char const **
) parameter of fts_open
. This parameter is described thus:
argv
Is a NULL terminated array of character pointers naming one or more paths that make up the file hierarchy.
So you need to create an array of length two whose elements are of type char*
. Put your path in the first element and put NULL in the second element. Like this:
char const *argv[] = { path, NULL };
You can now pass argv
to fts_open
.
fts_open
expects an array of char*
to be compatible with the main
function’s argv
array (and since char**
can’t be converted to char const**
).
So you need to create such an array. In particular, if you have a path in a char const*
variable, you must copy the string; e.g.:
char path_copy[PATH_MAX];
strcpy(path_copy, path);
char *argv[] = {path_copy, NULL};
FTS *fts = fts_open(argv, FTS_PHYSICAL, nullptr);
This is using a statically-sized buffer. Depending on your requirements you may want to dynamically allocate a buffer of appropriate size instead.
… it may be possible (likely, even) that fts_open
doesn’t actually modify its arguments, so casting away the const
instead of copying the string should be possible. But the documentation of fts_open
gives no such guarantee, so I advise against it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With