V
V
Vladimir A2020-11-09 15:16:58
linux
Vladimir A, 2020-11-09 15:16:58

How to read file in parts and write to const char**?

There is a file. Suppose its size is 50455 kb, I need to read it completely, but write it as const char * every 1024 kb.
What is the best way to do this?
I am writing under ubuntu, there is an internal read method, but with it you can read the entire file at once, is it possible to somehow do at the time of reading immediately form the final array from const char* ? Can this be done somehow correctly through fread?

This is how I, for example, read the entire file:

size_t filesize = (std::filesystem::file_size("путь"));
    char *buf = (char*) malloc(filesize);
    FILE *file = fopen("путь до файла", "b");
    fread(buf, 1, filesize, file);
    fclose(file);


something like this for reading in parts

char *inputData = malloc(dataLen);
    char *p = inputData;
    size_t bytesLeft = dataLen;
    while (bytesLeft) {
        size_t bytesRead = fread(p, 1, 1024, f);
        bytesLeft -= bytesRead;
        p += bytesRead;
        if (ferror(f) != 0) {
            fprintf(stderr, "ERROR: fread() failed\n");
            free(inputData);
            fclose(f);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Adamos, 2020-11-09
@Adamos

Well, you create a char** of size (dataLen + 1023) / 1024 and repeat this code for reading in parts, assigning to the next element of this array the created char* of size 1024, into which you read such a piece of data.

Q
qwerty123123, 2020-11-09
@qwerty123123


fstream fs("13w87wmd.exe", std::ifstream::binary);
const int len ​​= 1024;
char buff[len];
while(fs.readsome(buff, len)) {
cout << buff << endl;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question