C创建txt文件并将当前日期和时间附加为名称

时间:2014-08-21 07:47:36

标签: c file-io

我无法找到如何在C中创建txt文件,例如" test.txt"然后附加到文件名当前日期和时间?每次程序运行时都会创建test.txt但具有不同的日期和时间?这个。现在我只是使用带有标志的开放函数创建txt文件,但我不确定如何追加日期和时间?

 fd = open("test.txt", O_RDWR | O_CREAT | O_APPEND, 0777);

THX

3 个答案:

答案 0 :(得分:0)

您可以使用ctime.h库函数。

time_t time(time_t *)返回给您的当前时间。

要将其转换为格式化的时间字符串,请考虑使用struct tm * gmtime(time_t *)。

然后使用int sprintf(char *,const char * ...)来格式化文件名字符串。

花一些时间阅读这些图书馆文件:

时间(http://www.cplusplus.com/reference/ctime/time/

gmtime(http://www.cplusplus.com/reference/ctime/gmtime/

sprintf(http://www.cplusplus.com/reference/cstdio/sprintf/?kw=sprintf

答案 1 :(得分:0)

使用预定义的ctime功能:

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

int main(int argc, char* argv[])
{
    time_t current_time;
    FILE* file;

    current_time = time(NULL);

    file = fopen("test.txt", "w+");

    fprintf(file, "%s", ctime(&current_time));

    return 0;
}

使用strftime功能:

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

int main ()
{
    time_t rawtime;
    struct tm* timeinfo;
    char buffer[80];
    FILE* file;

    file = fopen("test.txt", "w+");

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer, 80, "%I:%M:%S", timeinfo);
    fprintf(file, "%s", buffer);

    return 0;
}

答案 2 :(得分:0)

我不确定你的代码是做什么的,所以这是你问题的最基本的实现。我想这可以帮到你。
    有更优雅的方法可以解决它,但我认为你应该从最底层开始并逐步实现

FILE *fp;

// insert the date into the char array
char text[17];
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(text, sizeof(text)-1, "%dd %mm %YYYY %HH:%MM", t);
text[16] = 0;

// concat the date to file name
char *filename;
if((filename = malloc(strlen("C:\\Temp\\filename.txt")+strlen(text)+1)) != NULL){
    filename[0] = '\0';   // ensures the memory is an empty string
    strcat(filename,"C:\\Temp\\filename");
    strcat(filename,text);
    strcat(filename,".txt");
}

// use the file
fp = fopen(filename, "w+");
fputs("This is testing for fputs...\n", fp);
fclose(fp);

希望有所帮助

相关问题