0

I am trying to write a program that can append a line to a text file(with input taken from the actual program) and that can delete a line with a certain word in it. When I either try to append the line at the end or simply delete a line it works as intended. The problem occurs when I add then delete a line (not necessarily the same line). If I do both operations, then the line that was just added is also deleted even if its not the line which the program meant to delete. Here is my code for the two operations:

void add(char *file, *char info){
     FILE *p = fopen(file, "wt"); // check for error
     fprintf(file, "%s\n", info);// close file;}

For delete, we only want to delete a single instance (first) of name

void delete(char *file, *char name){

   FILE *old = fopen(file, "rt");
   FILE *new = fopen("temp", "wt");
   char line[1000];
   fgets(line,999,old);
   int deleted = 0;
    while(!feof(csv_old)){
          if(strstr(line, name)==0 || deleted >= 1)
                    fputs(line, new);
            else if(strstr(line,name)!=0)
                    deleted++;
            fgets(line,999,old);}
    // close files

For example, if i have say:

this

that

this

Say I call add("filename", "those") then it appends "those" properly to the end of file (in the new file). but if I call add then immediately call delete on say "this", i get:

that

this

in the new file

I am completely stuck as to why this is. Any help would be greatly appreciated

mmmmo
  • 135
  • 2
  • 6
  • 1
    `fgets(line,1000,old);` is correct (or `fgets(line,sizeof line,old);`). (there is no `-1` with `fgets` -- it includes the `'\0'` in the size) You will want to look at [**Why is while ( !feof (file) ) always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – David C. Rankin Mar 22 '19 at 03:59
  • Please use an orthodox [indentation style](https://en.wikipedia.org/wiki/Indentation_style) for C — either Allman (my preference) or 1TBS. Close braces belong on new lines. In `add`, you zap the content of `file` when you use `fopen()` with `"wt"` — if you want to append, use `"at"`. You then misuse `file` instead of `p` in the call to `fprintf()`. – Jonathan Leffler Mar 22 '19 at 04:38
  • 1
    How are you planning to have the code delete a line? Normally, you will do it by opening a new file for writing, opening the original file for reading, reading lines from the original and writing all except those that must be delete to the new file. Then rename the original file, rename the new file, remove the renamed original file. Or copy the new file over the original (this preserves links and symlinks, but involves yet another copy of the file). – Jonathan Leffler Mar 22 '19 at 04:42
  • I didn't include the code where I delete the old file and rename the new one because I wanted to isolate the problem. For now, I am only looking at the "temp" file – mmmmo Mar 22 '19 at 14:10

0 Answers0