Created
September 20, 2016 19:59
-
-
Save dirkjanfaber/d0d5d90125529b139ae3b864ca1b82d4 to your computer and use it in GitHub Desktop.
Reading a value from file in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This example program reads a value from a file. This file can be updated | |
from another program, while this main program never needs to stop. | |
gcc -O2 -Wall -o readtempfromfile readtempfromfile.c | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
float read_temp_from_file() { | |
FILE *fp; | |
char buff[5]; // 5 characters ought to be sufficient. | |
fp = fopen("temp.txt", "r"); | |
fscanf(fp, "%s", buff); | |
fclose(fp); | |
float ftemp = atof(buff); | |
return ftemp; | |
} | |
int main (int argc, char **argv) { | |
// printf("Reading temperature from file: temp.txt\n"); | |
float temp = read_temp_from_file(); | |
while (1) { | |
printf("Current temperature: %0.2f\n", temp); | |
temp = read_temp_from_file(); | |
sleep(1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment