So I have a FIFO file that I made with mkfifo()
function in terminal and I'm sending data with : echo"12.5 123 5 -2.1" > rndfifo
My program needs to read those numbers and put them in a array so that I can use them later . I currently only succeeded in creating a program that reads those numbers and placing them in a char array, but I got stuck and have no clue how to continue so any help?
Code:
MSG_LEN defined at 16
int main(int argc, char **argv) {
if(2 != argc)
exit(EXIT_FAILURE);
int fd = open(argv[1], O_RDONLY);
if(-1 == fd);
exit(EXIT_FAILURE);
do {
char buf[MSG_LEN];
int bytesRead;
if(-1 == (bytesRead = read(fd, buf,MSG_LEN))){
perror("Reading from PIPE failed");
exit(exit_failure);
}
if (0 == bytesRead)
break;
printf("Read number: %d\n", atoi(buf));
} while (true);
close(fd);
return 0;
}
The solution for separating numbers that I wrote (Thanks Chintan)
(if there are any better ones please write them)
Also what can i do to stop the program if a pipe sends something else then a number?
char *deo;
float tmp;
deo = strtok(buf," ");
while(deo != NULL){
sscanf(deo,"%f",&tmp);
//tmp one number from buf(sent from FIFO)
deo = strtok(NULL," ");
}
After you have read the FIFO message, and placed the content in char array, take that char array and parse numbers from it, or stop the program if there is something else then a number. For reading numbers from char array use
double strtod(const char *nptr, char **endptr)
To see how to find out if there was some invalid character in char array read the first example and then refer to NOTE in the second (long) example.Longer example with getting average value from numbers in FIFO message. If you need to put those numbers in array, here is how (if you need to take the average, you don't even need to put them in array :) )
And at last, printArray and CHECKERR implementations: