-
Searching in file
Can u give me an example of function which search for a string in a file?
I want to make a phone book. Phone book must have options for add, delete and find numbers. I've already done the add function. Now I'm trying to make the find() function, but I don't know how. I'm plannig to make a find() function which will be returning the string which we are looking for and (1)will display it on the screen; (2) will be used for the delete() function - we will enter a string for deleting, this string will be given to the find() function and then if the string exist he will be deleted ( I don't know yet how ).
So I hope u understand me want I exactly want.
-
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;
}
-
I'm really appreciate your help! I've examed your code and I've got the idea! Now, I'll make my own code and I use it in my first C program :)