Linux&C:System()命令
我目前正在从事一个项目,该项目要求我在编写C代码时调用Linux命令。我在其他源代码中发现,我可以使用system命令执行此操作,然后将Linux shell的值保存到我的C程序中 例如,我需要将目录更改为Linux&C:System()命令,c,linux,system,iio,C,Linux,System,Iio,我目前正在从事一个项目,该项目要求我在编写C代码时调用Linux命令。我在其他源代码中发现,我可以使用system命令执行此操作,然后将Linux shell的值保存到我的C程序中 例如,我需要将目录更改为 root:/sys/bus/iio/devices/iio:device1> 然后输入 cat in_voltage0_hardwaregain 作为命令。这将向C输出一个double 因此,我的示例代码是: #include <stdio.h> #include
root:/sys/bus/iio/devices/iio:device1>
然后输入
cat in_voltage0_hardwaregain
作为命令。这将向C输出一个double
因此,我的示例代码是:
#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);
}
我知道这可能不是最好的方法,所以任何信息都非常感谢 您真正想做的是打开C程序并直接读取文件。通过系统调用使用cd和cat会造成妨碍 以下是简单的方法:
#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;
}
您的问题是什么?您不能使用子进程来更改您的工作目录,这就是为什么cd不是一个程序,而是一个shell内置程序。您需要在自己的进程中调用chdir,或者做一些合理的事情,使用新的*at版本的文件函数,比如openat,但它不是这样工作的。为什么不使用函数来读取文件?使用cat就像是用脑袋打膝盖,也许你会发现一颗神奇的子弹。那么,它应该是什么呢?Linux不是带有令人毛骨悚然的驱动器号的Windows。