0

I have this struct of people:

struct patient{
   char name[100];
   char address[100];
   int age;
}

struct patient p1;
int f;
f = open("patients.dat",O_RDWR,S_IRUSR|S_IWUSR);

And I wrote a binary file by using f = open... and write(f,&p1,sizeof(struct patient))

Now there is a task where I have to delete certain people from the binary file (for example those whose name I enter) I thought about changing the last person with the one I wanna delete, but then there is still the last one in the file to be deleted.

Is there any way to delete that from the file, I don't know, like changing the p1's name,address,and age to '\0', but it didn't work, it still shows "ghost" things.

1
  • 1
    You can't delete data from a file unless it is in the end of the file. What people usually do is to write a new file with edited data. Commented Oct 19, 2020 at 19:08

2 Answers 2

2

You cannot remove (or add) data from/to the middle of a file in POSIX -- only at the end. You can overwrite data in the middle, but that does not change the size of the file.

So if you want to delete a data record from the middle, you need to overwrite it with other data (possibly moving all subsequent data down, or possibly by just copying the last element), and then change the size to remove the last element (which is now a duplicate).

You change the size of a file with ftruncate

Sign up to request clarification or add additional context in comments.

2 Comments

Thought "that does not change..." -> "that can not change..."
So if I truncate the file with 1 struct smaller number then the last structure will be deleted?
0

And I wrote a binary file by using f = open... and write(f,&p1,sizeof(struct patient)).

Please read the documentation of open(2) and write(2) (and also of lseek(2), close(2), ftruncate(2), inode(7), credentials(7) ...).

You need to check the return value of open and write.

As with most other syscalls(2). See also errno(3) and read Advanced Linux Programming

You could adopt a convention (and document it): every patient entry (inside your binary file) whose name starts with a 0 byte is cleared and could be reused.

You might also consider using mmap(2) to access your binary file. This would work well if your binary file is not too big (less than a few gigabytes in 2020). see also this answer.

Actually, you could consider using some database library, such as sqlite. Or some indexed file library, such as gdbm.

And both sqlite and gdbm are open source software coded in C for Linux. You'll learn a lot by studying their source code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.