Delete last 10 characters from text file

Is there a way to remove the last 10 characters from a text file?

thanks

+3
source share
2 answers

For single-byte encoding on the POSIX platform, you can use something like this (error handling omitted):

FILE *file = fopen("filename", "a");
fseek(file, -10, SEEK_END);
ftruncate(fileno(file), ftell(file));    // POSIX function

It will not work for encodings with variable-length characters such as UTF-8 and UTF-16.

+9
source

For what will work under windows, you can do something like this:

FILE* pFileIn    = fopen( "filenameIn", "rb" );
FILE* pFileOut   = fopen( "filenameOut", "w+b" );

fseek( pFileIn, -10, SEEK_END );
long length    = ftell( pFile );

long blockSize = 16384;
void* pBlock   = malloc( blockSize );
long dataLeft  = length;
while( dataLeft > 0 )
{
   long toCopy = (dataLeft > blockSize) ? blockSize : dataLeft;

   fread( pBlock, toCopy, 1, pFileIn );
   fwrite( pBlock, toCopy, 1, pFileOut );

   dataLef     -= toCopy;
}

free( pBlock );

fclose( pFileIn );
fclose( pFileOut );
+3
source

Source: https://habr.com/ru/post/1715057/


All Articles