本文介绍了用C写入文件时要换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在Linux上编写程序,以从/proc/stat获取当前的CPU使用率并打印到.txt文件中.但是,在写入文件时,我无法打印新行,并且输出将覆盖旧行...

I am currently writting a program on Linux to get the current CPU usage from /proc/stat and print in to a .txt file. However, whilst writting to the file, I am unable to print a new line, and the output prints OVER the old one...

我想在上一行下打印新行,但是使用"\n""\r"字符无效.

I would like to print the new line under the previous one, but using the "\n" or "\r" characters didn't work.

代码在这里:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void checker();

int main(){

    long double a[4], b[4], loadavg;
    FILE *fp;
    char dump[50];

    for(;;){
        fp = fopen("/proc/stat","r");
        checker();
        fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&a[0],&a[1],&a[2],&a[3]);
        fclose(fp);
        sleep(1);

        fp = fopen("/proc/stat","r");
        checker();
        fscanf(fp,"%*s %Lf %Lf %Lf %Lf",&b[0],&b[1],&b[2],&b[3]);
        fclose(fp);

        fp = fopen("CPU_log.txt", "w");
        checker();
        loadavg = ((b[0]+b[1]+b[2]) - (a[0]+a[1]+a[2])) / ((b[0]+b[1]+b[2]+b[3]) - (a[0]+a[1]+a[2]+a[3]));
        fprintf(fp, "Current CPU Usage is: %Lf\r\n", loadavg);
        fclose(fp);
    }
    return 0;
}

void checker(){
    FILE *fp;
    if (fp == NULL){
    printf("Error opening file!\n");
    exit(1);
   }
}

推荐答案

似乎您需要向现有文件中添加新数据(即不要覆盖),而不是每次都创建空文件.试试这个:

It seems that you need to append new data to existent file (i.e. do not overwrite) instead of creating of empty file each time. Try this:

fp = fopen("CPU_log.txt", "a");

第二个参数"a"表示附加":

Second argument "a" means "append":

另外,修改功能checker似乎是可行的:

Also it seems reasanoble to modify your function checker:

void checker(FILE *fp) {
  if (fp == NULL){
    perror("The following error occurred");
    exit(EXIT_FAILURE);
  }
}

这篇关于用C写入文件时要换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:42
查看更多