Lukas Hejcman Lukas Hejcman - 3 months ago 12
C Question

New line while writing to file in C?

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

Answer

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(1);
  }
}