Ticket #886: read_file-load-directly-to-string.diff

File read_file-load-directly-to-string.diff, 1.1 KB (added by Nicolas, 15 years ago)
  • lib/util.cpp

    old new  
    341341int read_file_string(const char* path, string& result, size_t max_len, bool tail) {
    342342    result.erase();
    343343    int retval;
    344     char* buf;
     344    double size;
    345345
    346     retval = read_file_malloc(path, buf, max_len, tail);
     346    retval = file_size(path, size);
    347347    if (retval) return retval;
    348     result = buf;
    349     free(buf);
     348
     349#ifndef _USING_FCGI_
     350    FILE *f = fopen(path, "r");
     351#else
     352    FCGI_FILE *f = FCGI::fopen(path, "r");
     353#endif
     354    if (!f) return ERR_FOPEN;
     355
     356#ifndef _USING_FCGI_
     357    if (max_len && size > max_len) {
     358        if (tail) {
     359            fseek(f, (long)size-max_len, SEEK_SET);
     360        }
     361        size = max_len;
     362    }
     363#endif
     364    result.reserve(size);
     365    char buf[8192];
     366    size_t remain = size, to_read, nread;
     367    while (remain > 0) {
     368        to_read = sizeof(buf);
     369        if (remain < to_read) to_read = remain;
     370
     371        nread = fread(buf, 1, to_read, f);
     372        result.append(buf, nread);
     373
     374        remain -= nread;
     375    }
     376    fclose(f);
    350377    return 0;
    351378}
    352379