c++ - 依次打开两个文件

标签 c++

当尝试像这样一个接一个地打开两个文件时:

ofstream transactionFileList(file_day, std::ios_base::app);
transactionFileList << file_date << endl;
transactionFileList.close();


ofstream transactionFile(file_date);
for(int x = 0; x < _item_number_transaction.size(); x++){
    transactionFile << _item_number_transaction[x] << ":" << _quantity_transaction[x] << endl;
}
transactionFile.close();

我没有收到任何错误,但只创建了 transactionFileList

此外,当我 cout file_date 时,我得到 13-04-1995.txt 所以该变量没有问题!有什么想法吗?


变量

time_t t = time(0);
struct tm * now = localtime(&t);
char file_date[80];
char file_day[80];
strftime(file_date, 80, "%Y-%m-%d|%H:%M:%S.txt", now);
strftime(file_day, 80, "%Y-%m-%d_transactions.txt", now);

最佳答案

file_date 变量有无效的文件名,所以transactionFile 没有打开,你可以通过条件检查:

if (transactionFile) {
    // do something with stream...
}

file_date 包含不能在某些操作系统的文件名中使用的符号 |

我还建议使用 RAII 习语的强大功能,而不是显式调用 close():

{
    ofstream transactionFile(file_date);
    if (transactionFile) {
        for(int x = 0; x < _item_number_transaction.size(); x++){
        transactionFile << _item_number_transaction[x] << ":" <<  _quantity_transaction[x] << endl;
    } else {
        throw std::runtime_error("File not opened.");
    }
}

关于c++ - 依次打开两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29751659/

相关文章:

C++ 检查一个 double 是否在另一个 double (+/-) 的 .1 范围内

c++ - 2个类之间的双向关联

c++ - 全局 bool 变量在全局销毁期间是否可靠?

c++ - 编译器如何理解指针和数组的声明

c++ - 为什么我的程序同时进入 if 语句和相应的 else 语句?

c++ - 从 x32 迁移到 x64 时出现链接器错误

c++ - 不要为虚拟基类使用默认构造函数

c++ - 检测到 'vccorlib_lib_should_be_specified_before_msvcrt_lib_to_linker' : value '1' doesn't match value '0' in msvcrtd. 库不匹配

c++ - Qt - 在两种形式之间传递数据

c++ - OpenCV C++/Obj-C : Detecting a sheet of paper/Square Detection