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
コマンドを使用して、プログラムが本来の動作をするかどうかを確認できます。