Beispiel #1
0
bool ksfu_readEntireFile(const char* const path,
                         char** data,
                         size_t* length)
{
    struct stat st;
    if(stat(path, &st) < 0)
    {
        KSLOG_ERROR("Could not stat %s: %s", path, strerror(errno));
        return false;
    }

    void* mem = NULL;
    int fd = open(path, O_RDONLY);
    if(fd < 0)
    {
        KSLOG_ERROR("Could not open %s: %s", path, strerror(errno));
        return false;
    }

    mem = malloc((size_t)st.st_size);
    if(mem == NULL)
    {
        KSLOG_ERROR("Out of memory");
        goto failed;
    }

    if(!ksfu_readBytesFromFD(fd, mem, (ssize_t)st.st_size))
    {
        goto failed;
    }

    close(fd);
    *length = (size_t)st.st_size;
    *data = mem;
    return true;

failed:
    close(fd);
    if(mem != NULL)
    {
        free(mem);
    }
    return false;
}
Beispiel #2
0
bool ksfu_readEntireFile(const char* const path, char** data, int* length, int maxLength)
{
    bool isSuccessful = false;
    int bytesRead = 0;
    char* mem = NULL;
    int fd = -1;
    int bytesToRead = maxLength;

    struct stat st;
    if(stat(path, &st) < 0)
    {
        KSLOG_ERROR("Could not stat %s: %s", path, strerror(errno));
        goto done;
    }

    fd = open(path, O_RDONLY);
    if(fd < 0)
    {
        KSLOG_ERROR("Could not open %s: %s", path, strerror(errno));
        goto done;
    }

    if(bytesToRead == 0 || bytesToRead >= (int)st.st_size)
    {
        bytesToRead = (int)st.st_size;
    }
    else if(bytesToRead > 0)
    {
        if(lseek(fd, -bytesToRead, SEEK_END) < 0)
        {
            KSLOG_ERROR("Could not seek to %d from end of %s: %s", -bytesToRead, path, strerror(errno));
            goto done;
        }
    }

    mem = malloc((unsigned)bytesToRead + 1);
    if(mem == NULL)
    {
        KSLOG_ERROR("Out of memory");
        goto done;
    }

    if(!ksfu_readBytesFromFD(fd, mem, bytesToRead))
    {
        goto done;
    }

    bytesRead = bytesToRead;
    mem[bytesRead] = '\0';
    isSuccessful = true;

done:
    if(fd >= 0)
    {
        close(fd);
    }
    if(!isSuccessful && mem != NULL)
    {
        free(mem);
        mem = NULL;
    }

    *data = mem;
    if(length != NULL)
    {
        *length = bytesRead;
    }

    return isSuccessful;
}