将时间戳格式化为文本

时间:2013-07-03 10:37:06

标签: c linux unix sed awk

我想获取文件的修改日期,然后将其格式化为人类可读日期。我正在运行一个C程序,它获取有关上次修改特定文件的信息。 我的C代码包含一个系统cmd,其中包含许多egreps,awks,seds由管道分隔。使用sed或awk或类似的东西,我如何将06转换为6月(这可以是任何月份,因此需要数组或其他东西)我想要实现的是最终得到类似于的字符串:

我的C代码包含:

    char string1[100] = "";
    #define MAXCHAR 100
    FILE *fp;
    char str[MAXCHAR], str2[MAXCHAR];
    char* filename = "newfile";

    /*
    stat: run 'stat' on the dtlName file to display status information.
    egrep: search for the pattern 'Modify' and print the lines containing it.
    awk: Get columns 2 & 3
    sed: replace the . with a space, leaving 3 columns of output
    awk: only print cols 1 & 2 to newfile
    sed: replace '-' with ' ' in newfile
    awk: format output in newfile
    */
    sprintf(string1, "/bin/stat %s  \
                    | egrep Modify \
                    | /bin/awk '{print $2, $3}' \
                    | /bin/sed 's/\\./ /g' \
                    | /bin/awk '{print $1, $2}' \
                    | /bin/sed 's/-/ /g' \
                    | /bin/awk '{print $3,$2\", \"$1,\"at\",$4}' > newfile"
                    , dtlName);
    system(string1);
    fp = fopen(filename, "r");
    while (fgets(str, MAXCHAR, fp) != NULL)
            sprintf(str2,"%s", str);

    /*  Write information to file */
    DisplayReportFile (report);
    ReportEntry (report,L"Source file: %s, Created: %s\n\n",dtlName,str2);

5 个答案:

答案 0 :(得分:1)

通常你会使用fstat()和strftime()。

答案 1 :(得分:1)

为什么不使用

 #include <fcntl.h>
 #include <sys/types.h>
 #include <sys/stat.h>

 int stat(const char *restrict path, struct stat *restrict buf);

(来自man -s2 stat

这会给你一个time_t和上次修改的时间

然后您可以使用ctime_rasctime_rmktime来获取相应的信息。

答案 2 :(得分:1)

以下是同一程序的工作版本:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
        if (argc < 2) exit(1);

        char *filename = argv[1];

        struct stat st;
        char s[1000];
        if (stat(filename, &st))
                exit(2);

        struct tm *mdtime = localtime( &st.st_mtime );
        strftime(s, sizeof(s), "%D", mdtime);

        printf("%s\n", s);
}

有关更多格式,请参阅strftime

答案 3 :(得分:0)

awk sed组合是否必要?为什么不在文件上调用fstat并从那里提取修改日期?然后,您可以通过调用ctime()将其转换为字符串。

答案 4 :(得分:0)

我不知道它是否有用。但是,一旦我做了类似的事情。 获取该字符串只是处理该字符串并在此之后得到Month,您可以使用

if(strcmp(May,string1)==0)
return 5;

您可以获得所需的输出。

相关问题