如何将上次打开文件后经过的秒数转换为小时,分钟和秒?

时间:2014-10-04 07:51:35

标签: c time

我希望它看起来像“自上次打开文件以来已经过了00小时00分43秒。” 我怎么能这样做,所以数字仍然是整数,而不是浮点数?

#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 个答案:

答案 0 :(得分:1)

  1. 您的previousTime变量未初始化会导致result错误。
  2. 更改程序中语句的顺序就足以解决这个问题。

    #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;
    }
    
    1. 您对浮点值的提问尚不清楚,因为您的程序中没有float个变量,只有int