Concatenate two huge files in C++

后端 未结 4 1407
感动是毒
感动是毒 2021-02-06 01:55

I have two std::ofstream text files of a hundred plus megs each and I want to concatenate them. Using fstreams to store the data to create a single file usually ends up with an

4条回答
  •  醉酒成梦
    2021-02-06 02:06

    On Windows:-

    system ("copy File1+File2 OutputFile");
    

    on Linux:-

    system ("cat File1 File2 > OutputFile");
    

    But the answer is simple - don't read the whole file into memory! Read the input files in small blocks:-

    void Cat (input_file, output_file)
    {
      while ((bytes_read = read_data (input_file, buffer, buffer_size)) != 0)
      { 
        write_data (output_file, buffer, bytes_read);
      }
    }
    
    int main ()
    {
       output_file = open output file
    
       input_file = open input file1
       Cat (input_file, output_file)
       close input_file
    
       input_file = open input file2
       Cat (input_file, output_file)
       close input_file
    }
    

提交回复
热议问题