gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:27:03 25 4
gpt4 key购买 nike

因此,我尝试将“创建时间”和“上次修改时间”时间戳写入报告文件的顶部。代码看起来很简单,但是却行不通。文件的顶部应如下所示:

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() 正在执行任何操作。结果是三个始终反射(reflect)创建时间的时间戳。

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

最佳答案

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

关于c - 将时间修改标记写入文件顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com