Page 1 of 1

Delete Bytes From A Text File

Posted: Mon Nov 17, 2003 6:54 am
by Fresh
Hi,

I created a text file. Write 5 byes('ABCDE') to the file. After closing the file... I want to delete its last character('E') by reading all file contents and recreating a new one with same filename. Is it possible to do this in just one time 'fopen()'? Facing with problems when the file size is too big, large buffer used and very slow. My code as below :( :

[cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void create_file()
{
char str[] = {"ABCDE"};

FILE *fp = fopen("c:\\try.txt", "wb");
fwrite(str, 1, strlen(str), fp);
fclose(fp);
}

void remove_last()
{
long fsize;
char *buf = NULL;

// Read file contents...
FILE *fp = fopen("c:\\try.txt", "r+b");
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);

buf = (char*)malloc(fsize);
fread(buf, 1, fsize, fp);
fclose(fp);

// Reopen the file...
fp = fopen("c:\\try.txt", "wb");
fwrite(buf, 1, fsize - 1, fp);
fclose(fp);
free(buf);
}

void main()
{
create_file();
remove_last();
}
[/cpp]

-novice :-?

...

Posted: Wed Nov 19, 2003 9:44 am
by Fresh
Help!

Posted: Wed Nov 19, 2003 2:19 pm
by Dominik Michniewski
your code is right. But you have do something like this:

f = fopen(file);
// calculate offset - you can use ftell() to do this ...
fseek(f,offset,SEEK_SET); // move to first character to delete
fseek(f,skip_bytes,SEEK_SET); // how many bytes are to delete
while(/* not end of file - no of readed bytes != sizeof_data */)
{
fread(data,sizeof_data....);
fseek(f,-skip_bytes,SEEK_SET);
fwrite(data,.....);
fseek(f,skip_bytes,SEEK_SET);
}
fclose(f);

You don't need to reopen file, no need very large buffer and so on. But it maybe slower a bit - more disk reads and writes is neccessary

Best regards
DM

...

Posted: Wed Dec 03, 2003 4:41 am
by Fresh
I don't understand. Can I get the full code? :oops: What happen to the last bytes of the file... have they been deleted?

-novice