我正在尝试编写一个程序,在单独的文本文件中输出大量数据。我希望每个文件的标题为 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");
}
最佳答案
日期和时间字符串中可能包含对于您的文件系统来说可能不是合法字符的字符(例如冒号)。
关于c++ - 创建标题中带有时间戳的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15161914/