将时间修改的标记写入文件的顶部

时间:2014-10-23 22:11:28

标签: c time io timestamp logfile

所以我正在尝试将Time Created和Last Modified时间戳写在报告文件的顶部。代码看起来很简单,但它不起作用。 文件顶部应如下所示:

File created: *timestamp*
Last updated: *timestamp*

首次创建文件时,两个时间戳应该相同。在每次连续修改文件时,应更新第二个文件。但是,第二个时间戳似乎永远不会改变。这是代码。请注意,asctime()返回的字符串有一个内置的新行,我认为这是违反直觉的。

NewFile = 0;
//open for updating, or create
if(   (fid = fopen(FileName,"r+"))   ==    NULL){
    NewFile = 1;
    if(   (fid = fopen(FileName,"w"))    ==    NULL){
        fprintf(stderr,"%s: Could not access file\n",FileName);
        return 1;
    }
}

// Update time
time(&rawtime);
timestruct=localtime(&rawtime);

if(NewFile){
    fprintf(fid,"File created: %32s",asctime(timestruct)); //write the creation timestamp
}else{
    fgets(linebuffer,128,fid); //skip over the creation timestamp
}
printf("Last Updated: %s\n",asctime(timestruct)); //prints correct time to console
fprintf(fid,"Last Updated: %32s\n",asctime(timestruct)); //doesn't seem to have an effect on the file
//fprintf(fid,"Last Updated: %32s\n",asctime(timestruct));

fflush(fid);
fclose(fid);
return 0;

奇怪的是printf()语句将正确的时间输出到控制台。但等效的fprintf()语句不断改变原始时间。为了实验我添加了一个额外的fprintf语句,它与第一个语句相同(在上面的代码中注释掉)。这是为了确保fprintf()完全正在做任何事情。结果是三个时间戳总是反映创建时间。

我已经工作了很长时间,所以我的大脑已经死了。所以也许我错过了一些明显的东西。

1 个答案:

答案 0 :(得分:0)

尝试使用“w +”打开,在阅读和写作之间切换需要fseek。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main() {
    char linebuffer[256] = {0};
    int NewFile = 0;
    time_t rawtime;
    struct tm *timestruct;
    FILE *fid;
    //open for updating, or create
    if(   (fid = fopen("FileName","r+"))   ==    NULL){
        NewFile = 1;
        if(   (fid = fopen("FileName","w+"))    ==    NULL){// open with w+
            fprintf(stderr,"Could not access FileName\n");
            return 1;
        }
    }

    // Update time
    time(&rawtime);
    timestruct=localtime(&rawtime);

    if(NewFile){
        fprintf(fid,"File created: %32s",asctime(timestruct)); //write the creation timestamp
    }else{
        fgets(linebuffer,128,fid); //skip over the creation timestamp
        fseek ( fid, 0, SEEK_CUR);//switch from read to write
    }
    printf("Last Updated: %s\n",asctime(timestruct));
    fprintf(fid,"Last Updated: %32s\n",asctime(timestruct));// now writing

    fclose(fid);

    return 0;
}