2013-07-19 31 views
0

我寫了一些代碼來顯示上次修改的時間和文件名。我的代碼編譯,但我需要改變的時間戳格式如何更改我的打印輸出? (系統編程和C)

我要的是:
Jul 17 12:12 2013 2-s.txt
Jul 17 12:12 2013 3-s.txt

什麼,現在我得到的是:
Wed Jul 17 12:24:48 2013
2-s.txt
Wed Jul 17 12:24:48 2013
3-s.txt

有人可以看看我的代碼,並給我一些關於如何解決它的建議嗎?謝謝!!!

#include <sys/types.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <sys/utsname.h> 
#include <ctype.h> 
#include <string.h> 
#include <ar.h> 
#include <getopt.h> 
#include <time.h> 
#include <utime.h> 

int main (int argc, char **argv) 
{ 
    FILE *fp; 
    size_t readNum; 
    long long tot_file_size, cur_file_size; 
    struct stat fileStat; 
    struct ar_hdr my_ar; 
    struct tm fileTime; 
    struct utimbuf *fileTime2; 

    //open the archive file (e.g., hw.a) 
    fp = fopen(argv[1], "r"); 
    if (fp == NULL) 
    { 
     perror("Error opening the file\n"); 
     exit(-1); 
    } 

    //size of the archive file 

    fseek(fp, 0, SEEK_END); 
    tot_file_size =ftell(fp); 
    rewind(fp); 


    //read data into struct 
    fseek(fp, strlen(ARMAG), SEEK_SET);  //skip the magic string 



    while (ftell(fp) < tot_file_size - 1) 
    { 
     readNum = fread(&my_ar, sizeof(my_ar), 1, fp); 

     if (stat(argv[1], &fileStat) == -1) { 
      perror("stat"); 
      exit(EXIT_FAILURE);  //change from EXIT_SUCCESS to EXIT_FAILURE 
     } 

     if ((fileStat.st_mode & S_IFMT) == S_IFREG) 
     { 
      printf("%s", ctime(&fileStat.st_mtime)); 
      printf("%.*s", 15, my_ar.ar_name); 
     } 

     cur_file_size = atoll(my_ar.ar_size); 

     if (fseek(fp, cur_file_size, SEEK_CUR) != 0) 
     { 
      perror("You have an error.\n"); 
      exit(-1); 
     } 

    } 

    fclose(fp); 

    return 0; 
} 

回答

1

一旦你有你的struct tm時間,你可以使用strftime

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

int main() 
{ 
    struct tm *tp; 
    time_t t; 
    char s[80]; 

    t = time(NULL); 
    tp = localtime(&t); 
    strftime(s, 80, "%b %d %H:%M %Y", tp); 
    strcat(s, " 2-s.txt"); 
    printf("%s\n", s); 
    return 0; 
} 

輸出:

Jul 19 07:57 2013 2-s.txt 
+0

非常感謝你的提示!我注意到你使用當地時間。我需要使用文件的最後修改時間。有沒有辦法編輯它(例如,刪除前面的Wed)? – user2203774

+0

檢查[this](http://stackoverflow.com/questions/13542345/how-to-convert-st-mtime-which-get-from-stat-function-to-string-or-char) –