0

変数の (温度) 値を .txt に書き込むプログラムを C++ で作成しています。

この変数の値を file.txt の新しい行に常に挿入したいとします。この file.txt は次のようになります。

  • 37.0
  • 36.0
  • 37.1

最後の値の下に空白の改行なし (37.1)。ファイルは、この例では 1 の隣ではなく、最後の値の隣で終了する必要があります。

  • 37.0
  • 36.9
  • 37.1
  • 38.0(新データ)。

私はこのコードを作成しましたが、最後の値の下に空白の改行を作成せずに新しいデータを新しい行に配置する方法がわかりません。

#include <stdio.h>
#include <"eHealth.h>

int main(){
   while(1){
      float temperature = eHealth.getTemperature();
      FILE *myData;
      myData=fopen("file.txt","a");
      fprintf(myData,"%f",temperature);
      fprintf("%\n");
      fclose(myData);
      }
   return(0);
}

ありがとうございました!

4

1 に答える 1

0

を求めているので、コードは次のようになります。

#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;
}

プレーンなの場合:

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

于 2013-10-30T01:19:58.330 に答える