Reading a file and saving the same exact file c++ -


I'm actually writing a C ++ program that reads any type of file and saves it as a BMP file , But first let me read the file, and the issue was that

  four filenames [] = "test.jpg"; FILE * inFileForGettingSize; // This is the file size to get fopen_s (& inFileForGettingSize, filename, "R"); Fseek (inFileForGettingSize, 0L, SEEK_END); Int fileSize = ftell (inFileForGettingSize); Fclose (inFileForGettingSize); Ifstream inFile; // file it. The file has to be read (filename); If (inFile.fail ()) {cerr & lt; & Lt; "Error opening file" & lt; & Lt; Endl; } Char * data = new char [fileSize]; InFile.read (data, fileSize); Offream outfile; // File rewrite the file again. Open ("out.jpg"); OutFile.write (data, fileSize); OutFile.close (); Cin.get ();  

But when I read the file, it says a draft file, it finally produces some weird properties all the way, for example:

  assdassaasd sdaasddsa sdadsa  

passes by:

  assdassaasd sdaasddsa sdadsaÍ  

So when I Doing this with jpg, exe, etc. It's corrupt. I'm not trying to copy a file, I know that there are other ways for this, I'm just trying to read a full file byte byte. Thank you.

Edit:

I found that those 'Í' are equal to the number of last lines in the file, but this helps me a lot

This is the reason.

You open files in text mode (instead of "rb" instead of fopen > "r" And because you call ios :: binary to your firststream open ), and on Windows, text mode "\ r \ n" While writing joints to "\ n" and back "\ r \ n" the result is that the size of the disk size on the in-memory size Is going to be low, so when you try to write using the on-disk size, you can Memory tend to the end of the award array and memory that will be random stuff.

You will need to open files in binary mode while working with binary data:

  fopen_s (& inFileForGettingSize, fileName, "rb"); InFile.open (filename, ios :: binary); OutFile.open ("out.jpg", iOS :: binary);  

For future reference, your per-routine can be improved. Combining iostream with I / O seems weird, and opening and closing the file twice is extra work, and (most importantly), If your routine is ever to run on a large file, it will store the whole file in an attempt to load it in RAM. It would be better to copy one block at a time:

  const int BUFFER_SIZE = 65536; Four buffer [BUFFER_SIZE]; While (source.good ()) {source.read (buffer, buff) Dest.write (buffer, source.gcount ()); }  

Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -