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