Append item to a file before last line in c
The footer should update with current time and hour when a new Item added to the file. Here is the sample file format,
ITEM1
ITEM2 06/07/2010 10:20:22 //footer lineThe “ite开发者_开发问答m” has to append in the existing file, prior to the footer line, and the footer should be updated with new value. I am having to variables, “item” and “time” which hold the respective values as string.
After adding a new item (ITEM3) the file looks like,
ITEM1
ITEM2 ITEM3 07/07/2010 17:20:12 //changed footerHelp me to acheive this.
Since the footer line is a static length...
Seek to the beginning of the footer line, write the new item over it followed by a newline, then write out the new footer.
(Note that this procedure is dangerous if you can't guarantee that you will always write at least enough total bytes to overwrite the existing footer, but it looks like you have exactly that assurance here.)
My solution would be, fopen
with mode "r+" (reading and writing). fseek
backwards from the end, a buffer length's worth and fill it (placing the cursor at the end again), search the buffer backwards for the last newline (if there is none, search even further back and repeat), once it has been found (or you hit the beginning of the file), search to that position in the file (your read placed it somewhere else), and write your new item, followed by a new line followed by a new footer. Close the file and truncate
it to the right size.
HTH.
EDIT:
If the footer is always the same size, I'd definately go for Nicholas solution.
On a similar note; Whenever you modify a file, the file metadata changes to update the exact time of the last file write. You could always query that data with GetFileTime() on Windows.
It is easy. You only have to truncate the last line.
#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;
}
A simple (but not very efficient) algorithm could look like this:
string content = "";
string line = "";
// Append every but the last line to content
while(!eof(file))
{
content += line;
line = readline(file);
}
content += getNewItem();
content += generateFooter();
save(content);
精彩评论