I would like to pass a memory space to a callee to collect a string array which is filtered out from a file(i.e. /tmp/saveconfig, it is listed in the end of the question). Normally, it is supposed to have following output,
/dev/disk/by-id/scsi-2001b4d2039784462
/dev/disk/by-id/scsi-2001b4d2049798685
/dev/disk/by-id/scsi-2001b4d2032048753
More specificly, I assumed the caller, i.e. main(), just allocate a space by char *ptr = malloc(4096) and pass it to get_devs() and then free the space by caller. After organizing the array of strings in get_devs(), the caller can iterate the string from the allocated space by using char *dev[]. In other word, how can I correlate *ptr with *dev[]? But according to the snippet as below, I got segmentation fault. Where do I do wrong? Please give me a hint.
int get_devs(char *pdev[])
{
FILE *fp;
char str[64];
int len = 0, count = 0;
char *cp, *ptr;
/* opening file for reading */
fp = fopen("/tmp/saveconfig", "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while(fgets(str, 64, fp) != NULL) {
if (ptr = strstr(str, "/dev/")) {
for (len = 1, cp = ptr; *cp != '\n'; len++, cp++) {
if (*cp == '"') {
*cp = '\0';
break;
}
}
strncpy(*pdev, ptr, len);
printf("%s\n", pdev);
pdev++;
count++;
}
}
fclose(fp);
return count;
}
int main()
{
int i = 0, count = 0;
char *pdev[64];
count = get_devs(pdev);
for (; i < sizeof(pdev) / sizeof(*pdev); i++) {
printf("%s\n", pdev[i]);
}
}
The saveconfig file is as below,
{
"fabric_modules": [],
"storage_objects": [
{
"attributes": {
"block_size": 512,
},
"dev": "/dev/disk/by-id/scsi-2001b4d2039784462",
"name": "scsi-2001b4d2039784462",
"plugin": "block",
"readonly": false,
"write_back": false
},
{
"attributes": {
"block_size": 4096
},
"dev": "/dev/disk/by-id/scsi-2001b4d2049798685",
"name": "scsi-2001b4d2049798685",
"plugin": "block",
"readonly": false,
"write_back": false
},
{
"attributes": {
"block_size": 512,
},
"dev": "/dev/disk/by-id/scsi-2001b4d2032048753",
"name": "scsi-2001b4d2032048753",
"plugin": "block",
"readonly": false,
"write_back": false
}
]
}