New line while writing to file in C?

2019-07-25 12:04发布

问题:

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...

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

The code is here:

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

回答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");

Second argument "a" means "append":

Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.

Also it seems reasanoble to modify your function checker:

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


回答2:

Inside for loop, You are opening CPU_log.txt file in write mode.

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

Mode w will truncate the file to zero length or create file for writing.

Open file in append mode. This will not overwrite the contents.

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


回答3:

You need to open the files outside the for()-Loop, otherwise, your file is overwritten continuosly. Or you need to open your file with "a" instead of "w", which appends to the file instead of throwing everything away.

Besides, what is %Lf supposed to do? (Should be %f!)



标签: c fopen