這是很容易。您只需截斷最後一行。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NEWLINE "new line to append\n"
int main() {
FILE *file;
char *line = NULL;
size_t previous_line_offset = 0, line_offset = 0;
time_t time_signature;
// open data file
if((file = fopen("data.txt", "rw+")) == NULL) {
puts("ERROR: Cannot open the file");
return 1;
}
// find last line offset
while(!feof(file)) {
int n;
previous_line_offset = line_offset;
line_offset = ftell(file);
getline(&line, &n, file); // NOTE getline is a GNU extension
}
// append new line
fseek(file, previous_line_offset, SEEK_SET);
fputs(NEWLINE, file);
// apend signature
time(&time_signature);
fprintf(file, "%s", asctime(localtime(&time_signature)));
// free resources
fclose(file);
if(line)
free(line);
// voila!
return 0;
}
良好的靜態長度調用(假設它是,我認爲它不是),+1。 – falstro 2010-07-16 07:54:30
你可以請一個樣本片段尋求部分? – arun 2010-07-16 08:40:31
@arun; 'char footer [] =「00/00/0000 00:00:00 \ n」; FILE * f = fopen(「myfile」,「a +」); fseek( - (sizeof(footer)-1),SEEK_CUR)); fprintf(f,「我的下一個項目\ n」); fwrite(footer,1,sizeof(footer)-1,f); fclose(f);'sizeof上的-1是爲了移除字符串文字中的隱式空終止。 – falstro 2010-07-16 09:35:56