Read full contents of a file and return them in a std::string. * Returns a pair . * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string. * * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data * (with len > maxsize) will be returned. */
| 347 | * (with len > maxsize) will be returned. |
| 348 | */ |
| 349 | static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max()) |
| 350 | { |
| 351 | FILE *f = fopen(filename.c_str(), "rb"); |
| 352 | if (f == NULL) |
| 353 | return std::make_pair(false,""); |
| 354 | std::string retval; |
| 355 | char buffer[128]; |
| 356 | size_t n; |
| 357 | while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) { |
| 358 | // Check for reading errors so we don't return any data if we couldn't |
| 359 | // read the entire file (or up to maxsize) |
| 360 | if (ferror(f)) |
| 361 | return std::make_pair(false,""); |
| 362 | retval.append(buffer, buffer+n); |
| 363 | if (retval.size() > maxsize) |
| 364 | break; |
| 365 | } |
| 366 | fclose(f); |
| 367 | return std::make_pair(true,retval); |
| 368 | } |
| 369 | |
| 370 | /** Write contents of std::string to a file. |
| 371 | * @return true on success. |
no test coverage detected