如何将时间保存到文件中?

3

我有一个程序,可以将数据保存到文件中,并且我想在日志上放置当前日期/时间的时间戳,但是当我尝试将时间写入文件时,它不会显示出来,但我写入的其他数据可以。

#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <sstream>
#include <direct.h>
#include <stdio.h>
#include <time.h>

using namespace std;

string header_str = ("NULL");


int main()
{

for(;;)
{


        stringstream header(stringstream::in | stringstream::out);   

        header << "datasdasdasd_";

         time_t rawtime;

         time ( &rawtime );

        header << ctime (&rawtime);
        header_str = header.str();

        fstream filestr;

        filestr.open ("C:\\test.txt", fstream::in | fstream::out |   fstream::app | ios_base::binary | ios_base::out);

        for(;;)
        {
            filestr << (header_str);

        }

        filestr.close();


}

return 0;
}

有人知道如何修复这个问题吗?

3
为什么你的程序会出现无限循环? - Mitch Wheat
3
无限大的平方,实际上是无限大本身 :-) - paxdiablo
3个回答

5
这是我的做法,使用一个辅助函数,以你想要的格式提供日期和时间,包含在任何输出流中:
#include <time.h>
#include <iostream>
#include <fstream>
using namespace std;

// Helper function for textual date and time.
// DTTMSZ must allow extra character for the null terminator.

#define DTTMFMT "%Y-%m-%d %H:%M:%S "
#define DTTMSZ 21
static char *getDtTm (char *buff) {
    time_t t = time (0);
    strftime (buff, DTTMSZ, DTTMFMT, localtime (&t));
    return buff;
}

int main(void) {
    char buff[DTTMSZ];
    fstream filestr;
    filestr.open ("test.txt", fstream::out|fstream::app);

    // And this is how you call it:
    filestr << getDtTm (buff) << "Your message goes here" << std::endl;

    filestr.close();

    return 0;
}

这将创建名为test.txt的文件,并包含以下内容:
2010-05-05 13:09:13 Your message goes here

这个可以运行 xD 非常感谢(但是顺便提醒一下,你忘记了 #include <time.h>) - blood
好的,把它归咎于gcc太宽容了 :-) 为后代修复了它。 - paxdiablo

0

也许这个代码可以工作:

time_t rawtime;

time ( &rawtime ); header << "现在的时间是: %s" + ctime (&rawtime);

希望这个代码能够正常运行。


抱歉,无法将两个指针相加。 :( 好的,谢谢你的帮助。 - blood

0
一个非常好的提示是查看boost\date_time库。它很棒,拥有你需要的一切支持简单的输出和格式化,并且是可移植的。
值得一看。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接