如何避免向文本文件追加内容时重复写入表头行?
解决追加模式下重复写入表头的问题
嘿,这个问题我之前做类似记录程序的时候也踩过坑!你现在每次运行程序都会重复写入表头,根源在于不管目标文件有没有内容,你打开文件后都会直接输出表头行。要解决这个,核心就是在写入表头前先判断文件是否已经存在且包含内容,只有当文件是新创建的或者为空时,才写入表头。
方案一:使用C++17的std::filesystem(推荐)
C++17引入的文件系统库可以方便地检查文件状态,代码更简洁易读:
// StudyTime.cpp : /* 记录学习时长,接收用户输入并存储到.txt文件 */ #include "stdafx.h" #include <string> #include <iostream> #include <fstream> #include <iomanip> #include <filesystem> using namespace std; namespace fs = std::filesystem; int main() { string date = ""; double hours = 0; const string filename = "StudyTime.txt"; bool shouldWriteHeader = false; // 检查文件是否不存在,或者存在但为空 if (!fs::exists(filename) || fs::file_size(filename) == 0) { shouldWriteHeader = true; } ofstream myfile(filename, ios_base::app); // 以追加模式打开文件 if (shouldWriteHeader) { myfile << "Date" << setw(15) << "Study Time" << endl; // 仅在需要时写入表头 } // 接收用户输入 cout << "Date: "; cin >> date; cout << "Hours: "; cin >> hours; // 优化对齐逻辑,不用多个if-else int alignWidth = 16 - date.size(); // 可根据实际需求调整总宽度 myfile << date << setw(alignWidth) << hours << endl; myfile.close(); return 0; }
方案二:兼容旧C标准(无需C17)
如果你的编译器不支持C++17,可以通过尝试读取文件的方式判断是否有内容:
// StudyTime.cpp : /* 记录学习时长,接收用户输入并存储到.txt文件 */ #include "stdafx.h" #include <string> #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { string date = ""; double hours = 0; const string filename = "StudyTime.txt"; bool shouldWriteHeader = true; // 尝试以读模式打开文件,检查是否有内容 ifstream checkFile(filename); if (checkFile.is_open()) { char firstChar; checkFile.get(firstChar); // 如果读取到字符,说明文件已有内容,不需要写表头 if (!checkFile.eof()) { shouldWriteHeader = false; } checkFile.close(); } ofstream myfile(filename, ios_base::app); // 以追加模式打开文件 if (shouldWriteHeader) { myfile << "Date" << setw(15) << "Study Time" << endl; } // 接收用户输入 cout << "Date: "; cin >> date; cout << "Hours: "; cin >> hours; // 优化对齐逻辑 int alignWidth = 16 - date.size(); myfile << date << setw(alignWidth) << hours << endl; myfile.close(); return 0; }
额外优化点
我还帮你优化了日期长度判断的逻辑,原来的多个if-else可以用动态计算setw的数值来替代,这样不管日期是3位还是4位,都能保证对齐效果,代码也更简洁。
内容的提问来源于stack exchange,提问作者ZDOSA
相关产品推荐
相关产品推荐

