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);
}
}
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);
}
}
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");
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!)
Related
How can I check if a text file has something written or not. I tried:
LOGIC checkfile(char * filename)
{
FILE *pf;
pf=fopen(filename,"wt");
fseek(pf,0,SEEK_END);
if(ftell(pf)==0)
printf("empty");
}
This function returns empty everytime, even in my text file I have few words or numbers written.
The problem is that you opened the file for writing. When you do that, everything in the file is lost, and the length of the file is truncated to 0.
So you need to open the file for reading. And the easiest way to see if the file is empty is to try to read the first character with fgetc. If fgetc returns EOF, then the file is empty.
First of all: DO NOT OPEN THE FILE FOR WRITING!
second: for knowing about file status in C you can use fstat which is in sys headear file!
You can use struct stat for using this function
here is a simple example:
#include <sys/stat.h>
int main(void)
{
int fields = 0;
int size = 0;
// Open the file test.txt through open()
// Note that since the call to open directly gives
// integer file descriptor so we used open here.
// One can also use fopen() that returns FILE*
// object. Use fileno() in that case to convert
// FILE* object into the integer file descriptor
if(fields = open(file_path, "r")){
struct stat buf;
fstat(fields, &buf);
size = (int)buf.st_size;
}
printf("size of file is %d", size);
return 0;
}
Note: I just include a header file that related to fstat. You can add other header files yourself
What about using fscanf to read the file, and check if something was actually read?
FILE *fp;
char buff[255] = "";
fp = fopen(filename, "r");
fscanf(fp, "%s", buff);
if (!*buff)
printf("Empty\n");
else
printf("%s\n", buff);
fclose(fp);
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "ff.txt"
int main() {
char x[10],y[10];
FILE *fp;
fp = fopen(FILE_NAME, "r+");
if (fp == NULL) {
printf("couldn't find %s\n ",FILE_NAME);
exit(EXIT_FAILURE);
}
fprintf(fp,"Hello2 World\n");
fflush(fp);
fscanf(fp,"%s %s",x,y);
printf("%s %s",x,y);
fclose(fp);
return 0;
}
Here's a boiled down version of what I am trying to do. This code doesn't print anything in the console. If I remove the fprintf call, it prints the first 2 strings in the file, for me its Hello2 World. Why is this happening? Even after I fflush the fp?
After fprintf(), the file pointer points to the end of the file. You can use fseek() to set the filepointer at the start of the file:
fprintf(fp,"Hello2 World\n");
fflush(fp);
fseek(fp, 0, SEEK_SET);
fscanf(fp,"%s %s",x,y);
Or even better as suggested by #Peter, use rewind():
rewind(fp);
rewind:
The end-of-file and error internal indicators associated to the stream
are cleared after a successful call to this function, and all effects
from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to rewind allows to
switch between reading and writing.
It is always best to check the return code of fscanf() too.
To avoid buffer overflow, you can use:
fscanf(fp,"%9s %9s",x,y);
Im supposed to write a program that opens an excel file, reads the numbers on the file, multiplies them by 9.8 and the shows the answer in another excel gile.
I wrote this, and I did not get any errors in the compiler, but when I run it, it does not open any files. How do I make it open the files?
#include <stdio.h>
int main() {
FILE *archivo;
FILE *archivoSalida;
int masa;
float peso;
archivo = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoEntrada.txt", "r");
archivoSalida = fopen("C:/Users/nacho/Documents/UNAM/Informatica/proyecto/archivoSalida.txt", "r");
if (archivo != NULL)
{
printf("The file was opened succesully");
while (fscanf(archivo,"%d", &masa)!= EOF)
{
peso=masa*9.81;
fprintf(archivoSalida, "%f\n", peso);
}
}
else
{
printf ("Error");
}
fclose(archivo);
fclose(archivoSalida);
return 0;
}
You'll want to fopen the output file ("archivoSalida") with mode "w" (for write) instead of "r" (for read). See e.g. http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html.
You do check if the input file could be opened (if (archivo != NULL)). Why don't you do the same for the output file?
Upon an error, you should output which error occured from errno, e.g. via perror(...). That should help in finding the actual problem.
Your file denominated by archivoSalida is opened in read mode ('r').
You should also check the return codes of read/writes functions to be sure everything happen as wanted.
The file names look Windows-ish. Is it possible that all of the forward slashes (/) that you have in both file names should really be back slashes (\)?
By using c language I need to create a text file in /tmp directory, but I don't know how to do this. Is there anyone who knows how to create a text file in /tmp folder?
There's mkstemp function for this
Taken from here
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ("/tmp/myfile.txt","w");
if (pFile!=NULL)
{
//write
fclose (pFile);
}
return 0;
}
If /tmp/myfile.txt isn't there one will be created.
Here is an example:
char *tmp_file;
char buf[1000];
FILE *fp;
tmp_file = "/tmp/sometext.txt";
fp = fopen( tmp_file, "w" );
if ( fp == NULL ) {
printf("File open error! %s", tmp_file );
}
sprintf( buf, "Hello" );
fputs( buf, fp );
fclose( fp );
#include <stdio.h> // Defines fopen(), fclose(), fprintf(), printf(), etc.
#include <errno.h> // Defines errno
C programs generally start with the 'main()' function.
int main()
{
int rCode=0;
FILE *fp = NULL;
'fp' will be a reference to the file, used to read, write, or close the file.
char *filePath = "/tmp/thefile.txt";
'filePath' is a string that holds the path "/tmp" and the filename "thefile.txt".
The following line attempts to open the file in "write" mode, which (if successful) will cause the file "thefile.txt" to be created in the "/tmp" directory.
fp=fopen(filePath, "w");
Incidently, with the "w" (write) mode specified, it "thefile.txt" already exists in the "/tmp" directory, it will be overwritten.
The following code will print an error if the file could not be created.
if(NULL==fp)
{
rCode=errno;
fprintf(stderr, "fopen() failed. errno[%d]\n", errno);
}
After the file is created, it could be written to here:
fprintf(fp, "This is the content of the text file.\nHave a nice day!\n");
Now, the file can be closed.
if(fp)
fclose(fp);
All done.
return(rCode);
}
Several other people have mentioned that the correct way to do this is to use the mkstemp() function, that is because it will ensure your file has a unique name.
Here is a quick example of how to use it:
//Set file name
char filename[] = "/tmp/tmpfile-XXXXXX";
//Open the file in rw mode, X's replaced with random chars
int fd = mkstemp(filename);
//Write stuff to file...
write(fd, filename, strlen(filename));
//Close the file
close(fd);
//Do whatever else you want here, including opening and closing the file again
//Once you are done delete the temporary file
unlink(filename);
I left out error checking on purpose for clarity.
I have an embedded board (beagleboard-xm) that runs ubuntu 12.04. I need to read a GPIO continuously to see if the value of the port changes. My code is herebelow:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
FILE *fp;
int main(void)
{
//linux equivalent code "echo 139 > export" to export the port
if ((fp = fopen("/sys/class/gpio/export", "w")) == NULL){
printf("Cannot open export file.\n");
exit(1);
}
fprintf( fp, "%d", 139 );
fclose(fp);
// linux equivalent code "echo low > direction" to set the port as an input
if ((fp = fopen("/sys/class/gpio/gpio139/direction", "rb+")) == NULL){
printf("Cannot open direction file.\n");
exit(1);
}
fprintf(fp, "low");
fclose(fp);
// **here comes where I have the problem, reading the value**
int value2;
while(1){
value2= system("cat /sys/class/gpio/gpio139/value");
printf("value is: %d\n", value2);
}
return 0;
}
the code above reads the port continuously (0 by default), however, when I change the port as 1, system call output the correct value, however printf still prints 0 as an output. What is the problem with value2 that does not store the value that system() outputs.
If I use the code below instead of while loop above, I get an error about opening the value file (Cannot open value file.), if I put the fopen line outside of while loop, it does not show the changes in the value file.
char buffer[10];
while(1){
if ((fp = fopen("/sys/class/gpio/gpio139/value", "rb")) == NULL){
printf("Cannot open value file.\n");
exit(1);
}
fread(buffer, sizeof(char), sizeof(buffer)-1, fp);
int value = atoi(buffer);
printf("value: %d\n", value);
}
My question: how do I need to fix the code? or how should I read the value file?
As an additional info that I wonder: what is the difference to e.g. export the port by system("echo 139 > /sys/class/gpio/export") and fp = fopen("/sys/class/gpio/export","w"); fprintf(fp,"%d",139); which method do you suggest me to use? Why?
Thank you in advance.
The system() function returns the return value of cat, which is 0. It does not return the standard output from cat, which is what you were expecting.
I think the problem with your second bit of code is that you're not calling fclose(). Since you're running in a tight loop, you almost immediately exceed the number of open files allowed.
So, call fclose(), and think about putting a sleep() in there too.
When reading a file in C, your position in the file changes as you read it. For example, if you were to open a file with the contents:
First Line
Second Line
Third Line
and run this program:
char buffer[1024];
while(fgets(buffer, sizeof(buffer), theFile))
{
printf("Buffer: %s", buffer);
}
It would print:
First Line
Second Line
Third Line
As you read each line, the position in the file changes to the next line.
In your program, after reading the value the first time, you are trying to read the empty space in the file, instead of the value you want.
The solution to your problem is to move fopen outside of the while loop, but call fseek to reset your position to the start of the file each time through the loop.
To use fseek, you need to pass it a file pointer, byte offset and seek point. Here you call it on your file, with a 0 byte offset from the waypoint SEEK_SET, which indicates the start of the file.
fseek(theFile, 0, SEEK_SET);