tags:

views:

273

answers:

2

Hi, Is there any way to Delete last 10 characters from a text file ?

Thanks

+9  A: 

For single-byte encoding on 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 is not going to work for encodings with variable-length characters, such as UTF-8 and UTF-16.

qrdl
Is ftruncate() portable?
Vijay Mathew
this only works if the file is ascii.
Toad
@Vijay ftruncate() is POSIX function so it is portable to POSIX platforms.
qrdl
@qrdl - UTF-16 is as much a variable width encoding than is UTF-8. What you mean is the outdated UCS2.
edgar.holleis
UTF-8 is not the only problem. Other variable-length character encodings include UTF-16 (a surrogate pair represents one character, not two), shift-JIS, EUC-CN. And a UTF-8 character can occupy more than 2 bytes.
Steve Jessop
The number -10 assumes 10 bytes. That might be different than 10 characters.
hlovdal
Ok, ok. Indeed I meant UCS-2, not UTF-16. That's why I never use multibyte encoding. Good old ASCII (and sometimes EBCDIC) serves me just fine.
qrdl
Some of us sometimes speak to foreigners ;-)
Steve Jessop
Well, English is not my first language but still 8-bit encoding (not 7-bit!) is fine with me :)
qrdl
onebyone: one can still speak to foreigners in 8 bit using 'codepages'
Toad
I think the original question was about chars and not actual character codes. However, please, go no further until you read this. http://www.joelonsoftware.com/articles/Unicode.htmlAfter you are done, you are free to google for more accurate and deep introductions to the topic of encodings. I am tired of using programs written by people who still use "codepages" to speak with "foreigners".
jbcreix
+3  A: 

For something that will work under windows as well you could 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 );
Goz