Here's my attempt to replace first occurrence of pattern
in file with spaces. Effectively deleting it, and hopefully will allow me to "delete" it in a large file, without rewriting it.
#define MAX_LINE_LENGTH
int removeFirstOccurenceInFile(const char* fileName, const char* pattern) {
FILE* f = fopen(fileName,"r+");
if (f == NULL) {
perror("Can't open input file");
return 0;
}
char buf[MAX_LINE_LENGTH] = {'\0'};
char spaces[MAX_LINE_LENGTH];
int unreadBytes = 0;
char* patInBuf = NULL;
while (1) {
if (patInBuf != NULL) break;
unreadBytes += strlen(buf);
if (fgets(buf,sizeof(buf),f) == NULL) break;
patInBuf = strstr(buf,pattern);
}
if (patInBuf == NULL) {
fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
fclose(f);
return 0;
}
int delFrom = patInBuf-buf;
memset(spaces,' ',delFrom);
fseek(f,unreadBytes+delFrom, SEEK_SET);
fwrite(spaces,1,strlen(pattern),f);
fclose(f);
return 1;
}
I'm not sure about the error handling. I considered using goto
instead of the usual error handling:
if (patInBuf == NULL) {
fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
retval = -1;
goto cleanup;
}
...
cleanup:
fclose(f);
return retval;
Are there other problems? Will that indeed be efficient?