The task is to read the last 64kb file. If the file weighs less, then read it completely, and then overwrite it using the path W: \ Test.txt. But the trouble is that after writing at the end of the file, I get extra characters. If you open it with a regular notepad, then it is 4 letters “H”, if through Notepad ++, then this is what it means - “ออ”. What am I doing wrong?

#include <conio.h> #include <iostream> #include <cstdio> using std::cout; using std::endl; using std::cin; int main() { char filename [5000]; cout << "Hi! Enter the filename:"; gets_s(filename); errno_t err; FILE *pFile; err = fopen_s(&pFile, filename, "r"); long long nFileLen = 0; long long offset = 0; long long postfix = 65536; char * buffer; if (pFile) { fseek(pFile, 0, SEEK_END); nFileLen = ftell(pFile); if ((nFileLen - 65536) < 0) postfix = nFileLen; offset = nFileLen - postfix; fseek(pFile, offset, SEEK_SET); buffer = (char*)malloc(sizeof(char) * postfix); fread(buffer,1,nFileLen,pFile); fclose(pFile); } cout << sizeof(buffer); FILE *File; err = fopen_s(&File, "W:\Test.txt","wb"); fwrite(buffer, 1, postfix, File); fclose(File); } 

UPD: Clarified that these characters are added to replacements for the carriage return character - \r . That is, carriage transfer characters are ignored, and in return for them some left-wing data is added.

  • try rb mode. Practice on a file with two bytes: 0d 0a. sizeof (buffer) returns the size of the pointer, not the data. add else for pFile == nullptr. offset = max(nFileLen-postfix, 0); - jfs
  • Something weird in the code ... Why nFileLen fread try to read nFileLen bytes, when it is clear that in general nFileLen there are no bytes left but only postfix bytes left? (Yes, and you allocate memory exactly for postfix bytes.) What is the meaning of cout << sizeof(buffer); ? Why did the result record not fall under if (pFile) ? - AnT

1 answer 1

While I was waiting for clues from the guru, I figured it out myself. The fact is that I opened the file for reading as a text file (with the "r" flag), but it was necessary as a binary ("rb") file. That is, you need to fix err = fopen_s(&pFile, filename, "r"); err = fopen_s(&pFile, filename, "rb");