user1825770
user1825770

Reputation: 359

Deleting a string from a file

I'm coding in C. I have the following file ui.txt

user1 | 127.0.1.1
user2 | 127.0.1.1
user3 | 127.0.1.1

If I have a string str that is "user2", I need to find the line in ui.txt that has str, and delete that line so that I get

user1 | 127.0.1.1
user3 | 127.0.1.1

I have opened the file like this:

FILE *fp;
fp = fopen("ui.txt","a+");

I have opened it with a+ because any time I have to enter new info, say another user and their IP address, I have it append to the end of the file.

How do I go about this? Does it entail the use of fgetc or fgets? I've been using fgets so far. Please give me the complete code.

P.S. str can also be "user2 | 127.0.1.1" if that helps in simplifying the logic.

Upvotes: 0

Views: 5743

Answers (1)

cegfault
cegfault

Reputation: 6632

You are essentially asking the same thing as here: Delete a Line from a file in C Language, and also here: deleting a string from a particular position in a file

You will have to load the file into memory, edit it there, and then write it back to the disk.

Upvotes: 1

Related Questions