c - 如何将自上次打开文件以来经过的秒数转换为小时、分钟和秒?

标签 c time

我希望它看起来像“自您上次打开文件以来已经过去了 00 小时 00 分 43 秒。”。 我怎样才能使数字保持整数,而不是 float ?

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

int main(){
    int result,h,m,currentTime,previousTime;
    FILE *fp;

    currentTime=time(NULL);
    result=currentTime-previousTime;
    h=(result/3600);
    m=(result/60);


    fp=fopen("aeg.txt","r");

    if(fp==NULL){
        printf("No such file exists\n");
    }else{
        fscanf(fp,"%d",&previousTime);
        printf("It's been %d hours, %d minutes and %d seconds since you last opened the file",h,m,result);
        fclose(fp);
    }

        fp=fopen("aeg.txt","w");
        fprintf(fp,"%d",currentTime);
        fclose(fp);

    return 0;
}

最佳答案

  1. 您的 previousTime 变量未初始化,这导致结果错误。

改变程序中语句的顺序就足以解决这个问题。

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

int main(){
    int result,h,m,currentTime,previousTime;
    FILE *fp;

    fp=fopen("aeg.txt","r");

    if(fp==NULL){
        printf("No such file exists\n");
    }else{
        fscanf(fp,"%d",&previousTime);
        fclose(fp);
    }

    currentTime=time(NULL);
    result=currentTime-previousTime;
    h=(result/3600);
    m=(result/60);

    printf("It's been %d hours, %d minutes and %d seconds since you last opened the file",h,m,result);
    fp=fopen("aeg.txt","w");
    fprintf(fp,"%d",currentTime);
    fclose(fp);

    return 0;
}
  • 您关于浮点值的问题不清楚,因为您的程序中没有 float 变量,只有 int
  • 关于c - 如何将自上次打开文件以来经过的秒数转换为小时、分钟和秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190815/

    相关文章:

    可以映射零页或写入地址零吗?

    c - 打乱一个 float ?

    c - 如何从 C 中的字符串中删除最后几个字符

    linux - 需要 bash time 命令的功能才能运行

    linux - Linux时间命令的结果

    c - 通过管道将逐位加密传递到输出文件

    c - 一次又一次初始化时,指针在循环内做了什么?

    计算两个不同日期的两次时间之差

    string - 将工作日字符串解析为 time.Weekday

    c# - 如何更改 DateTime 中的时间?