如何确保我的"ifstream"文件对象指向的文件内容已更新?

How can I make sure that the file contents pointed to by my `ifstream` file object are updated?

本文关键字:quot 文件 已更新 对象 何确保 我的 ifstream 确保      更新时间:2023-10-16

我正在使用ifstream读取/proc/stat内核文件:

std::ifstream proc_stat_file("/proc/stat", std::ifstream::in);

此文件包含不同进程的 CPU 使用时间,并由内核频繁更新。我正在编写一个应用程序,该应用程序需要每秒记录解析此文件的总 CPU 时间。我已经在类的构造函数中使用ifstream打开过一次文件。我正在尝试读取类的成员函数中的文件内容:

void read_cpu_times()
{
std::string line;
const std::string cpu_string("cpu");
const std::size_t cpu_string_len = cpu_string.size();
while (std::getline(proc_stat_file, line)) {
// cpu stats line found
if (!line.compare(0, cpu_string_len, cpu_string)) {
std::istringstream ss(line);
// store entry
m_entries.emplace_back(cpu_info_obj());
cpu_info_obj & entry = m_entries.back();
// read cpu label
ss >> entry.cpu_label;
// count the number of cpu cores
if (entry.cpu_label.size() > cpu_string_len) {
++m_cpu_cores;
}
// read times
for (uint8_t i = 0U; i < static_cast<uint8_t>(CpuTimeState::CPU_TIME_STATES_NUM); ++i) {
ss >> entry.cpu_time_array[i];
}
}
}
// compute cpu total time
// Guest and Guest_nice are not included in the total time calculation since, they are
// already accounted in user and nice.
m_cpu_total_time = (m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_USER)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_NICE)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_SYSTEM)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IDLE)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IOWAIT)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_IRQ)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_SOFTIRQ)] +
m_entries[0].cpu_time_array[static_cast<uint8_t>(CpuTimeState::CS_STEAL)]);
//Reset the eof file flag and move file pointer to beginning for next read
//proc_stat_file.
proc_stat_file.clear();
proc_stat_file.seekg(0, std::ifstream::beg);

read_cpu_times()函数每秒调用一次。但是我在两次通话之间没有获得更新的m_cpu_total_time值。我不知道为什么。有什么想法吗?

我能够解决我的问题。文件内容正在更新,但我在每次读取文件后都没有清除我的m_entries向量。因此,它总是从向量m_entries的第一个元素读取,这将是第一次读取的数据,因为它从未被清除过。