gpt4 book ai didi

c++ - 如何确保我的 `ifstream` 文件对象指向的文件内容已更新?

转载 作者:行者123 更新时间:2023-11-28 04:07:43 25 4
gpt4 key购买 nike

我正在使用 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 vector 。所以它总是从 vector m_entries 的第一个元素开始读取,这将是第一次读取的数据,因为它从未被清除过。

关于c++ - 如何确保我的 `ifstream` 文件对象指向的文件内容已更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com