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.
offset = max(nFileLen-postfix, 0);- jfsnFileLenfreadtry to readnFileLenbytes, when it is clear that in generalnFileLenthere are no bytes left but onlypostfixbytes left? (Yes, and you allocate memory exactly forpostfixbytes.) What is the meaning ofcout << sizeof(buffer);? Why did the result record not fall underif (pFile)? - AnT