Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a const char* pointer to fts_open()

Tags:

c

How does one pass a const char *path to fts_open? I would like to pass a filePath.

like image 530
some_id Avatar asked Mar 28 '12 20:03

some_id


People also ask

Can a char * be passed as const * argument?

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 ...

Can const char * be reassigned?

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.

What is the const char* ptr?

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.

What is the difference between const char * and char * const?

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).


2 Answers

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.

like image 121
David Heffernan Avatar answered Oct 28 '22 09:10

David Heffernan


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.

like image 34
Konrad Rudolph Avatar answered Oct 28 '22 09:10

Konrad Rudolph