Blacklabel
Blacklabel

Reputation: 846

Delete a character from a file in C

How can I delete few characters from a file using C program?

I could not find any predefined functions for it.

To understand the purpose, I am trying to send a file through a socket, if N bytes are sent successfully, I want to delete those bytes from the file. At the end, the file will be empty. Any other way to do this efficiently?

Thanks Pradeep

Upvotes: 3

Views: 7323

Answers (5)

user379888
user379888

Reputation:

If the char's are one after the other than why dont you give a try to fseek();

Upvotes: 0

user415789
user415789

Reputation:

you should use an index which points to the beginning of the data you haven't sent yet. It is not necessary to delete what you have sent, just pass them, when you send the whole file delete it.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169488

There is no straightforward way to delete bytes from the beginning of a file. You will have to start from where you want to trim the file, and read from there to the end of the file, writing to the start of the file.

It might make more sense to just track how many bytes you have already written to the file in some other file.

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41686

Your way is pretty inefficient for large files, since you would have to copy "the rest of the file" some bytes further to the beginning, which costs much. I would rather record the "current sending position" somewhere outside of the file and update that information. That way, you don't have to copy the rest of the file so often.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799560

If they're at the end, truncate the file at the appropriate length. If they're not then you'll need to rewrite the file.

Upvotes: 4

Related Questions