Reputation: 1827
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
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:
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
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
Upvotes: 0