当您要求使用c++时,您的代码应如下所示:
#include <ofstream>
#include <chrono>
#include <thread>
int main() {
std::ofstream out("file.txt");
bool firstLine = true;
while(1) { // consider some reasonable shutdown condition, but simply
// killing the process might be sufficient
float temperature = eHealth.getTemperature();
if(!firstLine) {
out << std::endl;
}
else {
firstLine = true;
}
out << temperature;
out.flush();
// Give other processes a chance to access the CPU, just measure every
// 5 seconds (or what ever is your preferred rate)
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
return 0;
}
对于普通c做:
#include <stdio.h>
#include <unistd.h>
int main() {
FILE *out = fopen("file.txt","a");
if(out == NULL) {
perror("Cannot open 'file.txt'");
return 1;
}
bool firstLine = true;
while(1) { // consider some reasonable shutdown condition, but simply
// killing the process might be sufficient
float temperature = eHealth.getTemperature();
if(!firstLine) {
fprintf(out,"\n");
}
else {
firstLine = true;
}
fprintf(out,"%f",temperature);
fflush(out);
// Give other processes a chance to access the CPU, just measure every
// 5 seconds (or what ever is your preferred rate)
sleep(5);
}
fclose(out);
return 0;
}
提示:如果您在 *nix 之类的系统上测试您的代码,您可以简单地使用该tail -f file.txt
命令来查看您的程序是否执行了应有的操作。