Delete Bytes From A Text File

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

Delete Bytes From A Text File

Post 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 :-?

Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

...

Post by Fresh »

Help!

Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post 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
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)

Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

...

Post 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

Post Reply

Return to “C++”