0

I'm trying to delete a given line by replacing that line by the next line but it doesn't change anything

int i=0,n,j,p;
char s[80];
FILE *fp;
scanf("%d",&n);
fp = fopen("test.txt","r+");
while(fgets(s,sizeof(s),fp)!=NULL){
    i++;
    if(i==n)
        break;
    j = ftell(fp);
}

while(fgets(s,60,fp)!=NULL){
    p = ftell(fp);
    fseek(fp,0,j);
    fprintf(fp,"%s",s);
    j = p;
    fseek(fp,0,SEEK_CUR);
}
fclose(fp);
5
  • I don't think this will work for deleting the first line. You've already read past it when you set j.
    – Barmar
    Dec 29, 2018 at 0:18
  • I think your whole algorithm is messed up. If a line is shorter than the previous line, you'll overwrite only part of a line and then later read the rest of the replaced line. If the line is longer, you'll write too far. I haven't figured out precisely how to fix it, but it would be easier if you read fixed-size strings instead of reading by lines in the 2nd loop.
    – Barmar
    Dec 29, 2018 at 0:30
  • 1
    The fix to the problem @Barmar refers to is perhaps to move character-by-character rather than line-by-line. It is very inefficient. A simpler method may be to use a memory mapped file and simply memmove() the remainder of the file to the start of the line to be deleted.
    – Clifford
    Dec 29, 2018 at 0:43
  • @Clifford character-by-character is just a limiting case of fixed-size strings. Memory mapping is OS-specific. But you could also read the entire file into memory, seek to the line to be deleted, then write the part of the memory buffer after that line.
    – Barmar
    Dec 29, 2018 at 0:57
  • And in all these methods, you need to truncate the file after the final line, to remove the extra line at the end.
    – Barmar
    Dec 29, 2018 at 0:58

1 Answer 1

2

You have the wrong arguments in fseek(fp, 0, j);. The third argument needs to be one of the SEEK_xxx constants, so it should be fseek(fp, j, SEEK_SET);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.