Thursday, 14 July 2011

My own version of deleting a line from a file in C

Modified version of this: http://bhagwat-masalkar.blogspot.com/2008/10/delete-line-in-file-c-programming.html


   
    FILE *f;
    f = fopen(argv[4],"a");//filename as command line argument                                                                                

    fseek(f, 0, SEEK_END); //                                                                                                                 
    if (ftell(f) == 0)//new file, add opening root xml tag                                                                                    
      fprintf(f,"<runs>\n");
    else{ // file wasn't empty, delete the closing root xml tag                                                                               
      fclose(f);

      char tmp_str[100];
      FILE *temp;

      f = fopen(argv[4],"r");
      temp = fopen("timings.tmp.xml","wb");

      while(fgets(tmp_str,100,f) != NULL){
        if(strstr(tmp_str,"</runs>"))
          break;
        else
          fputs(tmp_str,temp);
      }

      fclose(f);
      fclose(temp);
      char * command = //concatenating strings to build up a unix command                                                                     
        malloc(snprintf(NULL, 0, "mv timings.tmp.xml %s", argv[4]) + 1);
      sprintf(command,"mv timings.tmp.xml %s",argv[4]);
      system(command);
      f = fopen(argv[4],"a");
    }

    // ... and this is why I hate C sometimes

2 comments:

  1. Yuck. That's definitely why to avoid C for anything like that. Just dump things to disk and get out of C as soon as you can, and do the rest with Python externally.

    ReplyDelete
  2. Ok course, this is probably what Python does under the hood....

    adrianj

    ReplyDelete