【发布时间】:2014-12-19 17:27:29
【问题描述】:
所以我正在尝试将创建时间和上次修改时间戳写入报告文件的顶部。代码看起来很简单,但它不起作用。 文件的顶部应如下所示:
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() 正在做任何事情。结果是三个始终反映创建时间的时间戳。
我已经工作了很长时间,所以我的大脑已经死了。所以也许我遗漏了一些明显的东西。
【问题讨论】:
-
始终只为“w+”打开文件,从不用于读取。使用 stat() 来确定文件是否已经存在,如果已经存在,则只更新时间戳。使用 fseek() 在文件中定位以写入“更新”时间戳。
标签: c time io timestamp logfile