How to use const char pointer returned from a function in this instance? (mongodb related)

655 views Asked by At

I'm having a bit of trouble with a a function that the mongodb c driver uses. The function in question looks like this:

gridfile_get_field (gridfile *gfile, const char *name) (returns const char *)

I'm attempting to use it in the following manner:

const char * field = "file";
char * filename;
filename = (char *)gridfile_get_field(&gfile, field);
FILE * file;
file = fopen("test.txt", "a+");
fprintf(file, "file contains: %s\n", filename);
fclose(file);

However, after execution, I see this in test.txt:

file contains: ^A
file contains: ^A
file contains: ^A

I'm not sure what I'm doing wrong. The field that I specify exists in all of my files that I store in gridfs, so I don't think that's the case (specifying something that doesn't exist just files in "file contains: " with no character afterwards). I guess I'm doing something wrong in regards to the pointers. If anyone has any suggestions, that'd be awesome.

EDIT:: The real declaration is

const char * gridfile_get_field (gridfile *gfile, const char *name);
2

There are 2 answers

0
the_man_slim On BEST ANSWER

Turned out to be an issue with the MongoDB C driver- it wasn't returning the correct information. I think that issue will be addressed in an upcoming release.

4
Jens Gustedt On

If you feel the need to cast the return value of a function, you are most likely doing something wrong.

First, you should declare filename as being char const* since this is what you expect the function to return.

Then, probably you don't have the correct prototype for the function. You should have got an include file that comes with it. As a last resort declare the prototype as

char const * gridfile_get_field (gridfile *gfile, const char *name);

(Your compiler is probably taking the function to return an int, cuts of the high order bits and re-interprets this as a char*)