我正在尝试编写一个程序,它在单独的文本文件中输出大量数据。我希望每个文件的标题为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");
}
我不知道这些'_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
它说:“Poker_log_17:18:13_03/01/13.txt:无效的争论 我想也许是'/'让它混淆,所以我删除日期,但它说只有时间版本的相同的东西。 – Magicaxis 2013-03-01 17:19:51
冒号也可能是一个问题,也取决于您的文件系统。 – 2013-03-01 17:32:09