I've got a bash script which outputs strings in the format Hostname IP MacAddr
and is read by my script in written in C. I am trying to split these 3 up into an array, and make it so that I'm able to store them into a Json-c object to produce something that looks like {Clients: [{Hostname: Value, IP: Value, MacAddr: Value}]}
.
Currently my program is able to read each string line by line and store it into an array (The array is initialised wrong just for testing purposes, I'm going to change that):
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);
}
Is anyone able to help me with this and steer me in the right direction? String manipulation in C is relatively new to me and I'm still trying to get my head round it!
Edit:
My function now looks like this:
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;
}
The output looks like this when I run it: { "Clients": [ "Hostname", "192.168.1.18", "XX:XX:XX:XX", "Hostname", "192.168.1.13", "XX:XX:XX:XX" ] }
Does anyone have any ideas what I'm doing wrong to stop it from breaking the list after every client? i.e
{
"Clients" : [
{
"Hostname" : "example.com",
"IP" : "127.0.0.1",
"MacAddr" : "mactonight"
},
{
"Hostname" : "foo.biz",
"IP" : "0.0.0.0",
"MacAddr" : "12:34:56:78"
}
]
}