0

我写了一些代码来显示最后修改的时间和文件名。我的代码可以编译,但我需要更改时间戳的格式

我想要的是:
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;
}
4

1 回答 1

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
于 2013-07-19T05:58:49.327 回答