writing data to afile in fixed amount causing it to repaet the data in file c++

StackOverflow https://stackoverflow.com/questions/15557147

  •  29-03-2022
  •  | 
  •  

Вопрос

I have this program and i want to read the data in small parts like 2 kb each and then write it to a file but when i try to do it its reading and writing my file four times. here is my code:

#include<fstream>
#include<iostream>

using namespace std;

ifstream::pos_type size; // use if file is larger than 2 gb

int main()
{
   char *memblock=0;    
   ifstream in("file.txt", ios::in | ios::binary | ios::ate);
   ofstream in1("file1.txt", ios::out | ios::binary | ios::ate);
   size = in.tellg();
   cout << "Size of file "<< size << endl;
   float sz= size/2048.0;
   int sizechck = ceil(sz);
   cout<< "size is "<<sizechck;
   if(in.is_open())
   {
      memblock = new char [2048];
      for (j=0;j<=sizechck;j++)
      {
         in.seekg (j*2048,ios::beg);
         in.read (memblock, 2048);
         in1.write(memblock,2048);
      }

   }
   system("pause");
   return 0;
}
Это было полезно?

Решение

You're reading and writing 4096 bytes, but you're seeking 2048. (you're writing to unallocated memory btw).

You don't need to seek at all. Read and write are moving the file pointer accordingly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top