The idea is very simple. To find a string in a file: open the file and start reading lines. Use strstr to test if the string you've read matches what you're looking for. To delete a string in a file, you'll probably want to use a temporary file to hold the intermediate contents. Read the file line by line and if it does not match the string you're looking for, write it to the temp file. When you get to the end, rewind both files and copy the temp file to the original. The end result is that you've removed the line you wanted to.
There are plenty of ways to do this efficiently, but they can get complicated. Here is how to do it easily:
Code:
#include <stdio.h>
#include <stdlib.h>
int find(const char *phone, char *database)
{
char buff[BUFSIZ];
FILE *dbase;
if ((dbase = fopen(database, "r")) == NULL) {
perror("find fopen");
return 0;
}
while (fgets(buff, sizeof buff, dbase) != NULL) {
if (strstr(buff, phone) != NULL)
return 1; /* Found */
}
fclose(dbase);
return 0; /* Not found */
}
int delete(const char *phone, const char *database)
{
char buff[BUFSIZ];
FILE *scratch = tmpfile();
FILE *dbase = fopen(database, "r");
int deleted = 0;
if (scratch == NULL) {
perror("delete tmpfile");
return 0;
}
if (dbase == NULL) {
perror("delete fopen");
fclose(scratch);
return 0;
}
while (fgets(buff, sizeof buff, dbase) != NULL) {
if (strstr(buff, phone) != NULL) {
deleted = 1;
continue;
}
fputs(buff, scratch);
}
if (deleted != 0) {
rewind(scratch);
if ((dbase = freopen(database, "w", dbase)) == NULL) {
perror("delete freopen");
fclose(scratch);
fclose(dbase);
return 0;
}
while (fgets(buff, sizeof buff, scratch) != NULL) {
if (strstr(buff, phone) == NULL)
fputs(buff, dbase);
}
}
fclose(scratch);
fclose(dbase);
return deleted;
}
int main(void)
{
printf("Find string: %s\n", find("test", "test") ? "FOUND" : "NOT FOUND");
printf("Delete string: %s\n", delete("test", "test") ? "DELETED" : "NOT DELETED");
return 0;
}