just ME
just ME

Reputation: 1827

append text at the end of a line in a file pure c code

I need to append a text at the end of each line in a file. I have the following code:

FILE *tmp_copy = tmpfile();
file = fopen ( argv[2], "rw" );    
if ((file != NULL )) {
    char line [ 128 ]; /* or other suitable maximum line size */
    while( ( fgets ( line, sizeof line, file ) != NULL ))  {
       fputs(line, tmp_copy);
    }
    fclose ( file );

        rewind(tmp);
        char *p;
      /* Reopen file now with write permissions */
        fopen(argv[2], "w");
        while (( p = fgets(line, 1024, tmp))!=NULL) {
            //line[strlen(line)-1] = '\0'; /* Clear away newline */
            //sprintf(line, "%s %s\n", line, more);
            strcpy(line,"true");
            //fputs(line, file);
        }
fclose(file);
fclose(tmp);
            }

}

I ve edited my code. still not working but it's not working. why?

Upvotes: 1

Views: 2573

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

I'm guessing you want the line to be re-written to the file again. However, you are not writing to the file, just appending to the data in memory. It's also really not possible to read and write files at the same time like that, you have to do it in two steps:

  1. Read from original file, appending wanted text to line, and write to temporary file
  2. Rename (or copy) from temporary file to the original file

Edit: Pseudo-ish code for my answer:

original_file = fopen(original_file_name, "r");
temporary_file_name = tmpnam("dummy");
temporary_file = fopen(temporary_file_name, "w");

while (fgets(line, original_file))
{
    remove_trailing_newline(line);
    strcat(line, " TRUE\n");
    fputs(line, temporary_file);
}

fclose(temporary_file);
fclose(original_file);

rename(temporary_file_name, original_file_name);

Upvotes: 4

John Dvorak
John Dvorak

Reputation: 27317

Unless the file is memory-mapped AND fgets returns a pointer to the original buffer (it doesn't. It needs to append the null.) AND strcat operates in place (it does), then you are not storing anything, only messing up some memory. Even if it did work, you would overwrite a part of the next line anyways. You need to either

  • Write to a temporary file and rename that after you close the original one (as suggested by Joachim Pileborg).
  • Write into a buffer in memory and save it to the file when you are done reading.
  • Read the file into memory in one go, then start reading the buffer line by line.

Upvotes: 0

Related Questions