I'm trying to create a function that given a word in input can find and delete the line that contain it. I've done some research on internet and I wrote some code but when i launch the program only find the line but it doesn't delete the line and the old file (database.txt).
This is the function that deletes the line:
FILE *database, *database2;
char str[500];
int linea = 0, ctr = 0;
char ID[256];
database2 = fopen("database2.txt", "a");
fclose(database2);
database = fopen("database.txt", "r");
if(!database){
printf("Errore nell'apertura del file.\n");
getch();
return;
}
database2 = fopen("database2.txt", "r");
if(!database2){
printf("Errore nell'apertura del file 2.\n");
getch();
return;
}
printf("Inserisci l'ID del libro da eliminare:");
scanf("%s", &ID);
int x = FindLine(ID);
printf("%d", x);
while(!feof(database)){
strcpy(str, "\0");
fgets(str, 256, database);
if(!feof(database)){
ctr++;
if(ctr != x){
fprintf(database2, "%s", str);
}
}
}
fclose(database);
fclose(database2);
remove("database.txt");
rename("database2.txt", "database.txt");
getch();
This is the function that find the line:
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
fp = fopen("database.txt", "r");
if(fp == NULL){
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
return line_num;
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if(fp) {
fclose(fp);
}
return(0);
Some can help me to find the error please.