2010-05-05 20 views
1

我有一个程序,将数据保存到文件,我想要在当前日期/时间的日志,但当我试图写入文件的时间它不会显示,但我写其他数据将。我如何节省时间到一个文件?

#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

为什么你有一个无限循环? – 2010-05-05 04:09:58

+3

无限居然平方:-) – paxdiablo 2010-05-05 04:12:13

+1

无限乐趣=的xD – blood 2010-05-05 04:47:46

回答

3

这是我怎么会做它,与只给你你想要的格式的日期和时间纳入到任何输出流的辅助函数:

#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 
+0

嗯这部作品的xD tyvm(顺便说一句,但你忘了#包括) – blood 2010-05-05 16:03:15

+0

好点,责备它在gcc上如此宽容:-)修复它为后代。 – paxdiablo 2010-05-05 16:24:00

0

也许这会工作吗?:

time_t rawtime;

时间(& rawtime); 标题< <“时间是:%s”+ ctime(& rawtime);

希望这个作品

+0

遗憾没有 “错误C2110:‘+’:不能添加两个指针” :(Ø好谢谢你的好意 – blood 2010-05-05 05:06:42

0

一个非常好的技巧是检查出boost\date_time library。它是伟大的,它得到了你需要的一切支持简单的输出和格式化,并且是便携式的。

值得检查。