-3

I am currently working on a project that requires me to call a Linux command during a C code. I have found on other sources that I can do this using the system() command and then save the value for the Linux shell to my C program.

For example, I will need to change the directory to

 root:/sys/bus/iio/devices/iio:device1> 

and then input

 cat in_voltage0_hardwaregain

as the command. This should output a double into the C.

So my sample code would be:

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

double main() {
   char directory[] = "cd /sys/bus/iio/devices/iio:device1>";
   char command[] = "cat in_voltage0_hardwaregain";
   double output;

   system(directory);
   output = system(command);

   return (0);
}

I know this probably not the best way to do this, so any information is greatly appreciated.

Sam Protsenko
  • 14,045
  • 4
  • 59
  • 75
Dwhite
  • 1
  • 3
  • What is your question? – John Kugelman Mar 15 '16 at 21:22
  • 1
    You cannot use a child process to change your working directory, which is why `cd` is not a program but a shell builtin. You need to call `chdir()` in your own process, or do the sane thing and use the new `*at()` versions of file functions (like `openat()`). – EOF Mar 15 '16 at 21:24
  • It does not work like that. Why not use a function to read the file? Using `cat` seems like shooting your head through the knee (maybe you find a magical bullet, though). – too honest for this site Mar 15 '16 at 21:31
  • And what is `root:/` supposed to be? Linux is not Windows with creepy drive-letters. – too honest for this site Mar 15 '16 at 21:38

1 Answers1

4

What you really want to do is have the C program open and read the file directly. Using cd and cat via the system call just get in the way.

Here's the easy way to do it:

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

int
main(int argc,char **argv)
{
    char *file = "/sys/bus/iio/devices/iio:device1/in_voltage0_hardwaregain";
    FILE *xfin;
    char *cp;
    char buf[1000];
    double output;

    // open the file
    xfin = fopen(file,"r");
    if (xfin == NULL) {
        perror(file);
        exit(1);
    }

    // this is a string
    cp = fgets(buf,sizeof(buf),xfin);
    if (cp == NULL)
        exit(2);

    // show it
    fputs(buf,stdout);

    fclose(xfin);

    // get the value as a double
    cp = strtok(buf," \t\n");
    output = strtod(cp,&cp);
    printf("%g\n",output);

    return 0;
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48