2013-03-01 36 views
2

我正在尝试编写一个程序,它在单独的文本文件中输出大量数据。我希望每个文件的标题为Poker_Log_timestamp_datestamp.txt 但是,它并不实际创建文件,也不会抛出任何错误!在标题中创建一个带有时间戳的文本文件

下面的代码:

#include <fstream> 
#include <iostream> 
#include <ctime> 
#include <string> 
using namespace std; 

int main(){ 
    char sdate[9]; 
    char stime[9]; 
    fstream log; 
    _strdate_s(sdate); 
    _strtime_s(stime); 
    string filename = "Poker_Log_"; 
    filename.append(stime); 
    filename.append("_"); 
    filename.append(sdate); 
    filename.append(".txt"); 
    cout<<"Filename == "<<filename<<endl; 
    log.open(filename.c_str()); 
    log<<"\n\nHuman won the tournament.\n"; 
    log.close(); 
    system("Pause"); 
} 

如何使这项工作? 另一件事:如果我注释掉filename.append(stime)filename.append(sdate),它工作正常。

已解决:D文件名不能有任何斜杠或冒号,所以我用短划线替换它们。这里是工作代码:

#include <fstream> 
#include <iostream> 
#include <ctime> 
#include <string> 
#include <cstdio> 

using namespace std; 

int main(){ 
    char sdate[9]; 
    char stime[9]; 
    ofstream log; 
    _strdate_s(sdate); 
    _strtime_s(stime); 
    string filename = "Poker_Log_"; 
    filename.append(stime); 
    filename.append("_"); 
    filename.append(sdate); 
    filename.append(".txt"); 
    for(int i = 0; i<filename.length(); ++i){ 
     if (filename[i] == '/' || filename[i] == ':') 
      filename[i] = '-'; 
    } 
    log.open(filename.c_str()); 
    if (log.fail()) 
     perror(filename.c_str()); 

    log<<"\n\nHuman won the tournament.\n"; 
    log.close(); 
    system("Pause"); 
} 
+1

我不知道这些'_strdate_s'和'_strtime_s'函数是什么,但是如果在'log.open'之前的'cout << ...'行打印出您期望打印的内容,那么您的问题*不*与文件名的构造。你不检查'log.open'中的错误 - fstreams通过抛出一个异常不会*(默认)信号失败。如果在'log.open'行之后加上'if(log.fail())perror(filename.c_str());',它会打印什么? (可能需要添加'#include '来编译。) – zwol 2013-03-01 16:08:55

+0

它说:“Poker_log_17:18:13_03/01/13.txt:无效的争论 我想也许是'/'让它混淆,所以我删除日期,但它说只有时间版本的相同的东西。 – Magicaxis 2013-03-01 17:19:51

+1

冒号也可能是一个问题,也取决于您的文件系统。 – 2013-03-01 17:32:09

回答

3

日期和时间字符串中可能包含字符(如冒号),这些字符可能不是您文件系统的合法字符。

+0

冒号是非法呢?!aaaaaah就是这样!*开始编码* 酷:D现在错误信息已改为'(文件名):没有这样的文件或目录' – Magicaxis 2013-03-01 17:34:06

+0

明白了:D必须改变'fstream log' 'ofstream日志'谢谢! – Magicaxis 2013-03-01 17:36:13

2

使用以下命令:

log.open(filename.c_str()); 

open方法需要char *,又名C风格的字符串,而不是C++ std::string

+0

我试过了,似乎没有什么区别:( – Magicaxis 2013-03-01 17:12:58

相关问题