Hello Grincheux,
What do you mean, with, some parts might be locked ?
The Strings in the File are not listed straight.
Sting one
String two
String three
But instead somewhere randomly.
String one
String two
String three
Perhaps this prevents the funciton to find and delete the Strings as well ?
In this Code it is deleted well, but not ever :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define file "test_str_del.txt"
char carV[256];
void deleteElement() {
FILE *fp;
char value[256];
value[strcspn(value, "\r\n")] = 0; // new add, instead "s" now it is "val"
printf("Data to delete : ");
if(fgets(value,sizeof(value),stdin) == NULL) { // new add
printf("Wrong Input\n");
}
fp = fopen(file, "rb");
int keylen = strlen(value);
value[--keylen] = 0; // remove CR and fix keylen
if (fp) {
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *pbuf = malloc(len+1);
if (pbuf) {
fread(pbuf, len, 1, fp);
fclose(fp);
fp = NULL;
char *p1 = pbuf, *p = pbuf;
while (p = strstr(p, value)) {
if (!fp){ fp = fopen(file, "wb");}
fwrite(p1, p - p1, 1, fp);
p += keylen;
p1 = p;
}
if (p1) { // write rest of text
fwrite(p1, (pbuf + len) - p1, 1, fp); // doesn't execute
//printf("file almost finished");
}
}
fclose(fp);
}
}
void killNL(char *str) {
size_t p = strlen(str);
if(str[p-1] == '\n') {
str[p-1] = '\0';
}
}
void addNewElement(void) {
printf("Data to input : ");
if(fgets(carV, 256, stdin) == NULL) {
fprintf(stderr, "Wrong Input\n");
return;
}
killNL(carV);
FILE *fp = fopen(file, "ab");
if(fp == NULL) {
printf("Error in open: %s\n", file);
exit(EXIT_FAILURE);
}
if(fwrite(&carV, sizeof(carV), 1, fp) != 1) {
fprintf(stderr, "Error in write, in %s\n", file);
fclose(fp);
return;
}
fclose(fp);
}
int main(void) {
addNewElement();
addNewElement();
deleteElement();
return 0;
}
Thanks