c - Segmentation fault (core dumped) error with strcpy() (suspected) -


i having trouble trying runtime segmentation fault in short piece of code. suspect has use of system() , strcpy() in code not experienced type of error, unsure , have not found many helpful pages far.

the code:

#include <stdio.h> #include <string.h> int main(){         char command[31], string[128];         strcpy(string, (char *)system("grep -po '(?<=teststring\\s)\\s+' file"));         string[strlen(string)] = '\0';         printf("%s", string);         return 0; } 

i using gcc 4.7.3 compile program. appreciate lot.

the system command returns -1 on error or return status of command otherwise.

type casting integer return value causing segmentation fault in case.

to copy output of command buffer use popen returns file pointer file * can read command output.

here code:

#include <stdio.h> #include <stdlib.h>   int main( int argc, char *argv[] ) {    file *fp;   char string[128];     /* open command reading. */   fp = popen("grep -po '(?<=teststring\\s)\\s+' file ", "r");    if (fp == null) {         printf("failed run command\n" );         exit;   }    /* read output of command */   while (fgets(string, sizeof(string)-1, fp) != null) {         printf("%s", string);   }    /* close */   pclose(fp);    return 0; } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -