hari
hari

Reputation: 9733

delete content of the line that file pointer is pointing to

my file pointer is pointing to end of a line. I want to remove all contents of that line, how do I do that?

I might need to move the file pointer to start of the line and then delete the contents.

Upvotes: 2

Views: 1490

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490178

You can only delete from the end of a file. To delete data from the middle of a file, you generally need to copy the subsequent data to cover up the gap (or, more easily as a rule, make a new copy of the file, skipping over the part you want to delete).

If you need to do things like this very often, you'll probably want to create some sort of indexed file so you can just delete from the index -- or, of course, use a database library to handle it for you.

Upvotes: 2

Blrfl
Blrfl

Reputation: 7003

You have to shift all of the content beyond the line back to the location where the line to be deleted begins.

If you're working in an environment that supports it, you could mmap(2) the file, work with the whole thing in memory and use memmove(3) to make the shifts.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320541

You can't "delete" anything from a file. In C language files are accessed through streams, and streams don't support such operation as "delete a line" or "delete" anything at all. You can delete the entire file, but that's apparently not what you need.

Within the C language approach to working with files, all you can do is copy your original file to another file, skipping the line in question. The second file will look like the original one with the line deleted. After doing that you can destroy the original file and use the new one in its place.

There's a chance you might mean something else by your "delete" (what does your "delete" mean, BTW?). You might want to overwrite the contents of the line with space characters, for one example. If so, just move the current file pointer to the beginning of the line and write the appropriate number of space characters to the file.

Upvotes: 1

Related Questions