Question

I am relatively new to programming. What I am trying to accomplish is to write to a FIFO file I think its called. Basically if I am at a terminal window I can execute the command echo "0=0" > /dev/pi-blaster it will work as intended. So what I want to do is write a program that will basically execute that command for me but change the numbers between the double quotes. I know how to change the numbers with a loop I am just having trouble getting it to actually write the file. There are no errors being generated during compilation or running it simply does not function as if I were to type the command above. Like I said I am new to programming so maybe I am not even on the right path. I have included my code below:

#include <stdio.h>
#include <stdlib.h>

   int main(void)
   {
      FILE *fp;
      int i;

      fp = fopen("/dev/pi-blaster", "w");
      if (fp == NULL) {
         printf("I couldn't open pi-blaster for writing.\n");
         exit(0);
      }

      for (i=0; i<=10; ++i)
         fprintf(fp, "echo %d=%d", i, i*i);

      return 0;
   }
Was it helpful?

Solution

What you are doing is writing the actual echo shell command to the file, not e.g. 0=0.

You should only do

fprintf(fp, "%d=%d\n", i, i * i);

PS. You don't need to worry about flushing the file buffers, it will be done automatically when the file is closed, and the file will be closed when the process exits (but it's considered good to explicitly close files that you open, even if it's not technically needed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top