Split a binary file into chunks c++

Posted by L4nce0 on Stack Overflow See other posts from Stack Overflow or by L4nce0
Published on 2012-09-29T03:10:01Z Indexed on 2012/09/29 3:37 UTC
Read the original article Hit count: 120

Filed under:
|
|

I've been bashing my head against trying to first divide up a file into chunks, for the purpose of sending over sockets. I can read / write a file easily without splitting it into chunks. The code below runs, works, kinda. It will write a textfile and has a garbage character. Which if this was just for txt, no problem. Jpegs aren't working with said garbage.

Been at it for a few days, so I've done my research, and it's time to get some help. I do want to stick strictly to binary readers, as this need to handle any file.

I've seen a lot of slick examples out there. (none of them worked for me with jpgs) Mostly something along the lines of while(file)... I subscribe to the, if you know the size, use a for-loop, not a while-loop camp.

Thank you for the help!!

vector<char*> readFile(const char* fn){
    vector<char*> v;
    ifstream::pos_type size;
    char * memblock;
    ifstream file;
    file.open(fn,ios::in|ios::binary|ios::ate);
    if (file.is_open()) {
        size = fileS(fn);
        file.seekg (0, ios::beg);
        int bs = size/3; // arbitrary. Actual program will use the socket send size
        int ws = 0;
        int i = 0;
        for(i = 0; i < size; i+=bs){
            if(i+bs > size)
                ws = size%bs;
            else
                ws = bs;
            memblock = new char [ws];
            file.read (memblock, ws);
            v.push_back(memblock);
        }
    }
    else{
        exit(-4);
    }
    return v;
}


int main(int argc, char **argv) {
    vector<char*> v = readFile("foo.txt");
    ofstream myFile ("bar.txt", ios::out | ios::binary);
    for(vector<char*>::iterator it = v.begin(); it!=v.end(); ++it ){
        myFile.write(*it,strlen(*it));
    }
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about parsing