从C写入.text

时间:2013-10-30 00:40:18

标签: c++ c

我正在用C ++制作一个应该将变量(温度)值写入.txt的程序。

假设我想在新行的file.txt中不断插入此变量的值。这个file.txt应该是这样的:

  • 37.0
  • 36.0
  • 37.1

在最后一个值(37.1)下面没有空白换行符。该文件应该在最后一个值旁边,而不是在下面,在本例中,在1.旁边。但是如果要在文件中插入新数据,我想在下面插入(37.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);
}

谢谢!

1 个答案:

答案 0 :(得分: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命令来查看你的程序是否做了它应该做的事情。