2013-03-01 38 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

相關問題