【问题标题】:writing time modified stamp to the top of a file将修改后的时间戳写入文件顶部
【发布时间】: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


【解决方案1】:

尝试使用“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;
}

【讨论】:

  • 只添加了 fseek() 并修复了它。我没有意识到这是一个要求。我不会在 C 中做太多 I/O。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 2023-03-08
  • 2019-01-27
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2019-07-01
相关资源
最近更新 更多