我有一个 bash 脚本,它以格式输出字符串,Hostname IP MacAddr
并由我用 C 编写的脚本读取。我试图将这 3 个拆分为一个数组,并使其能够将它们存储到Json-c 对象生成看起来像{Clients: [{Hostname: Value, IP: Value, MacAddr: Value}]}
.
目前我的程序能够逐行读取每个字符串并将其存储到一个数组中(该数组被初始化错误只是为了测试目的,我将改变它):
int get_list_of_connected_clients(json_object *input, json_object *output) {
FILE *fp;
char path[1035];
int i = 0;
char a[2][100];
fp = popen("./Sample_Bash_Script_Test.sh", "r");
if (fp == NULL) {
printf("Failed To Run Script \n");
exit(1);
}
while (fgets(path, sizeof(path) - 1, fp) != NULL) {
stpcpy(a[i], path);
i++;
}
pclose(fp);
}
有没有人能够帮助我并引导我朝着正确的方向前进?C 中的字符串操作对我来说相对较新,我仍在努力解决它!
编辑:
我的函数现在看起来像这样:
int get_list_of_connected_clients(json_object* input, json_object* output){
FILE *filepath;
char output_line[1035];
int index=0;
char arr_clients[30][100];
filepath = popen("./Sample_Bash_Script_Test.sh", "r");
if (filepath == NULL){
printf("Failed To Run Script \n");
exit(1);
}
while (fgets(output_line, sizeof(output_line)-1, filepath) != NULL){
stpcpy(arr_clients[index], output_line);
index++;
}
pclose(filepath);
/*Creating a json object*/
json_object * jobj = json_object_new_object();
/*Creating a json array*/
json_object *jarray = json_object_new_array();
json_object *jstring1[2][2];
for (int y=0; y < 2; y++) {
int x = 0;
char *p = strtok(arr_clients[y], " ");
char *array[2][3];
while (p != NULL) {
array[y][x++] = p;
p = strtok(NULL, " ");
}
for (x = 0; x < 3; ++x) {
jstring1[y][x] = json_object_new_string(array[y][x]);
/*Adding the above created json strings to the array*/
json_object_array_add(jarray,jstring1[y][x]);
}
}
/*Form the json object*/
json_object_object_add(jobj,"Clients", jarray);
/*Now printing the json object*/
printf ("%s",json_object_to_json_string(jobj));
return 0;
}
当我运行它时,输出如下所示:{ "Clients": [ "Hostname", "192.168.1.18", "XX:XX:XX:XX", "Hostname", "192.168.1.13", "XX:XX:XX:XX" ] }
有没有人知道我做错了什么来阻止它在每个客户之后打破列表?IE
{
"Clients" : [
{
"Hostname" : "example.com",
"IP" : "127.0.0.1",
"MacAddr" : "mactonight"
},
{
"Hostname" : "foo.biz",
"IP" : "0.0.0.0",
"MacAddr" : "12:34:56:78"
}
]
}