Thread: Read/Write/Performance

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    5

    Read/Write/Performance

    Hello
    I want to read in a file binary (manipulate it) and write it back to a file. In other words I would like to copy a file.
    Code:
            ifstream in("file1.dat",ios::binary);
            ofstream out("file2.dat",ofstream::binary);
             
            in.seekg(0, ios::end);
            unsigned long file_size = in.tellg();
            in.seekg(0, ios::beg);                        
    
            char *buffer;
            buffer = new char [file_size];
            in.read(buffer,file_size);
            out.write(buffer,file_size);
    I thought this code should do it but I tried to copy a 1.11KB big file and the result file was just 1KB. Why? And is this an efficient way to read and write or is there a quicker possibility?

    Later I need to read the file bytewise so I would do it with
    Code:
    in.read(buffer,1);
    out.write(buffer,1);
    is this fast or is in.get() faster...?

    Thanks in advance.
    slapy

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Probably the fastest way to copy a file in C++ is:
    Code:
    out<< in.rdbuf();
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Also you have this:
    > ofstream out("file2.dat",ofstream::binary);
    Which should be:
    ofstream out("file2.dat",ios::binary);

    That's probably why it only copied 1KB vs 1.11KB.

Popular pages Recent additions subscribe to a feed