-2

can anyone please let me know how can i use following gawk command in c ? like we use some shell commands inside c using "system" function. further i want to give the number in below command ie 6,2,8 as parameters.

gawk -v FIELDWIDTHS='6 2 8' 'NR!=1 && x==$1{printf(" %d:%d",strtonum("0x"$2),strtonum("0x"$3)); next}; {x=$1; printf("%s%s %d:%d", NR==1?"":"\n", $1,strtonum("0x"$2),strtonum("0x"$3))}; END{print ""}' input.txt | sed '/^[0-9a-f]* [0-9:]*$/d' > result.txt

thanks, any help will be greatly appreciated.

Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
mezda
  • 3,537
  • 6
  • 30
  • 37
  • 4
    And why can't you just use system() to call it? – Wes Hardaker Mar 15 '12 at 13:51
  • i tried using system(), but i get the following error : prog.c:73: error: `s' undeclared (first use in this function) prog.c:73: error: (Each undeclared identifier is reported only once prog.c:73: error: for each function it appears in.) prog.c:73: error: syntax error before string constant prog.c:73: error: stray '\' in program – mezda Mar 15 '12 at 13:56
  • 1
    @user1182722 You need to escape the quotas and the backslashes when inserting it into the string literal: `...$1{prinf\" %d:%d\",...`, `...:\"\\n\",...` and so on. – praetorian droid Mar 16 '12 at 02:21
  • @praetoriandroid : thanks for your help. now using escape sequences as you told doesn't give error. But i get a new problem now. To check this, i used a small gawk statement (unlike a big one above) i.e i used, `char cmd[200]; sprintf(cmd,"gawk '{printf\" %s\", $0};' input.txt "); system(cmd);` . Now this gets compiled, but on running i am getting the segmentation fault. please let me know what is the issue here. thanks. – mezda Mar 16 '12 at 09:18
  • @user1182722 The code you provided works well. Please update your question with exact new code snippet. – praetorian droid Mar 16 '12 at 10:53
  • @praetoriandroid : now its working, wherever i am using %d for field arguments like $1,$2 etc, i need to use %%d ie escape seq for % also. thanks. – mezda Mar 19 '12 at 11:25

1 Answers1

1

You could probably construct the string with the variables using snprintf and then pass the command to popen which returns a file with the output. For example:

char buffer[1024];
snprintf(buffer, sizeof(buffer), "<insert command here>", var1, var2);
FILE output = popen(buffer, "r");

I'm aware that you directed the output to result.txt in your command, however if you are just going to use the output in your c program the file returned by popen should be enough. I haven't tried this myself so let me know if it works.

glindste
  • 1,427
  • 12
  • 14