[英]How to pass STDIN to a program and store its output to a variable? C
[英]C Program - How to read a file and store its texts in a variable?
請耐心等待,因為我還是編程新手。 我需要閱讀/proc/cpuinfo
來確定路由器的型號,文件如下所示:
system type : bcm63xx/HW553 (0x6358/0xA1)
machine : Unknown
processor : 0
cpu model : Broadcom BMIPS4350 V1.0
BogoMIPS : 299.26
wait instruction : yes
microsecond timers : yes
tlb_entries : 32
extra interrupt vector : yes
hardware watchpoint : no
isa : mips1 mips2 mips32r1
ASEs implemented :
shadow register sets : 1
kscratch registers : 0
core : 0
VCED exceptions : not available
VCEI exceptions : not available
我需要存儲在變量中的是這部分bcm63xx/HW553 (0x6358/0xA1)
。 這是型號,它不斷變化,這是我迄今為止嘗試過的:
#include <stdio.h>
int main ( void )
{
char filename[] = "/proc/cpuinfo";
FILE *file = fopen ( filename, "r" );
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); //print the file contents on stdout.
}
fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}
return 0;
}
但是那個腳本只打印文件,我不知道如何將路由器的模型存儲在變量中,我該怎么做?
PS:將路由器的模型存儲在變量中后,我需要比較它是否與預定義的變量匹配。
更新
我試圖使它成為一個函數,我的代碼是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* model() {
char filename[] = "/proc/cpuinfo";
char* key = "system type";
char* value;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line[1000];
char* router_model = NULL;
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
router_model = strdup(value);
break; // once the key has been found we can stop reading
}
}
fclose(file);
if (router_model != NULL) {
printf("The model is %s\n", router_model); // print router model
}
else {
printf("No %s entry in %s\n", key, filename); // key not found, print some error message
}
free(router_model);
}
else {
perror(filename); //print the error message on stderr.
}
return router_model;
}
int main(void)
{
char* ret;
ret = model();
printf("Model: %s\n", ret);
return 0;
}
但我收到一個錯誤:
test.c: In function ‘model’:
test.c:37:9: error: ‘router_model’ undeclared (first use in this function)
return router_model;
^~~~~~~~~~~~
test.c:37:9: note: each undeclared identifier is reported only once for each function it appears in
我如何解決它 ?
一旦你有了你的行,檢查它是否以你正在尋找的關鍵字符串開頭。
char* key = "system type";
...
if (strncmp(line, key, strlen(key)) == 0) {
/* this is the line you want */
}
確定該行后,找到第一個冒號。
char* value = strchr(line, ':');
現在你有了這個值,雖然它會包含前導冒號和空格,所以你可以遍歷它們。
value += 2;
然后你應該能夠使用這個結果。 請注意,我沒有分配任何新空間。 如果您想將此值保存在某處,則需要復制該字符串。 最簡單的方法是復制它。
char* router_model = strdup(value);
一旦你完成它,你將不得不free()
這個字符串。
你要這個:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char filename[] = "/proc/cpuinfo";
char* key = "system type";
char* value;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line[1000];
char* router_model = NULL;
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
router_model = strdup(value);
break; // once the key has been found wen can stop reading
}
}
fclose(file);
if (router_model != NULL)
printf("The model is %s\n", router_model); // print router model
else
printf("No %s entry in %s\n", key, filename); // key not found, print some error message
free(router_model);
}
else {
perror(filename); //print the error message on stderr.
}
return 0;
}
這是稍加修改和一些注釋的代碼。
請注意,仍有改進的余地。
使用strtok和strip,trim實現上面程序的鍵值對。這樣鍵的比較容易,問題的邏輯清晰。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char *strip(char *str){
if(str == NULL){
return str;
}
int j = 0;
while(str[0] != '\0' && isspace(str[0])){
j=0;
while(str[j] != '\0'){
str[j] = str[j+1];
j++;
}
}
return str;
}
char *trim(char *str){
if(str == NULL){
return str;
}
int len = strlen(str)-1;
while(isspace(str[len])){
str[len]='\0';
len--;
}
return str;
}
int process_line(char *str, char *res_key, char *res_value){
char *key, *value;
key = strtok(str, ":");
value = strtok(NULL, ":");
if( key && value){
key = strip(key);
key = trim(key);
value = strip(value);
value = trim(value);
//printf("%s:%s\n", key, value);
strcpy(res_key, key);
strcpy(res_value, value);
}
}
int main(int argc, char *argv[])
{
char filename[] = "/proc/cpuinfo";
char* key = "system type";
char* value;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line[2048]={0x00};
char temp_key[1024]={0x00};
char temp_value[1024]={0x00};
while (fscanf(file, " %[^\n]s", line) != EOF) /* read a line from a file */ {
process_line(line, temp_key, temp_value);
if(strcmp(temp_key, key) == 0){
break;
}
memset(line, 0x00, sizeof(line));
memset(temp_key, 0x00, sizeof(temp_key));
memset(temp_value, 0x00, sizeof(temp_value));
}
fclose(file);
printf("model:%s\n", temp_value);
}
else {
perror(filename);
}
return 0;
}
我認為這應該可以解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.