2016-03-15 127 views
-3

我目前正在研究一个需要我在C代码期间调用Linux命令的项目。我发现在其他来源中,我可以使用system()命令执行此操作,然后将Linux shell的值保存到我的C程序中。Linux&C:System()命令

例如,我需要将目录改变为

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

,然后输入

cat in_voltage0_hardwaregain 

作为命令。这应该输出出双入C.

所以我的示例代码如下:

#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); 
} 

我知道要做到这一点这可能不是最好的方式,所以任何信息是极大的赞赏。

+0

什么是你的问题? –

+1

你不能使用子进程来改变你的工作目录,这就是为什么'cd'不是一个程序,而是一个shell内建的。你需要在你自己的进程中调用'chdir()',或者做一些理智的事情,并使用新的'* at()'版本的文件函数(如'openat()')。 – EOF

+0

它不这样工作。为什么不使用函数来读取文件?使用'猫'似乎是通过膝盖射击你的头(也许你会发现一个神奇的子弹,虽然)。 – Olaf

回答

3

你真正想要做的是打开C程序并直接读取文件。使用cdcat通过system调用只是挡道。

这里是最简单的方式做到这一点:

#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; 
}