File reading in buffer identical methods between C and C++?

125 Views Asked by At

I was using the Jansson C library to parse some JSON file and using the method used in the sample file I tried to parse it using C-like code:

FILE *f = fopen(json_path.c_str(), "r");
fseek(f, 0L, SEEK_END);
long size = ftell(f);
fseek(f, 0L, SEEK_SET);
char* data = (char*)malloc((size + 1) * sizeof(char));
long rd = fread((void*)data, 1, size, f);
json_t* root = load_json(data);

While this code works well if compiled with gcc, it doesn't if it is compiled by g++ as it was the case for me as it was implemented in a C++ class. The errors returned by the Jansson library was about end of file characters.

At that point I tried implementing a more elegant C++-like code to do that:

std::ifstream f(json_path.c_str());
if (f) {
  std::stringstream s;
  s << f.rdbuf();
  f.close();
  json_t* root = load_json(s.str().c_str());
}

And that code never fails while it seems to me both should do quite the same.

Did I make a mistake in my C-like code in order to read the file in a whole buffer ? How the C++ compilation interpret the C-like code so end of files characters can "disappear" ?

1

There are 1 best solutions below

2
On BEST ANSWER

You need to add a terminator for the C code. It's just dumb luck that you get away with it in some cases and other times not:

char* data = malloc(size + 1);
long rd = fread(data, 1, size, f);
data[size] = '\0';

Note that in the C++ version c_str() kindly provides a C string terminator for you.