Reputation: 93
I need to send a string to a C program using a bash script, and then take that string in the C program and do things to it. The issue is I can't figure out how to use the string. I tried printf to see what the c program actually got, and it printed out random numbers.
This is the bash script:
length=`/home/hellboy632789/linelength $line`;
This is the C Program:
int main(int argc, char *argv[])
{
int length;
char *string = argv[1];
for(length = 0; string[length] != '\0'; length++);
printf("%d\n", length);
return(0);
}
I am fairly new to C, but any help would be greatly appreciated.
Upvotes: 0
Views: 688
Reputation: 747
You are returning the length of the string as the exit code of the C program. Bash makes that exit code available in the variable $?
.
Your bash script, on the other hand, is putting into your "length" variable what your C program is printing to stdout, which is not at all the same thing.
Since the exit code is conventionally 0 if the program executed correctly, and non-zero if there was an error, it makes more sense to use the bash script as such and change the C code.
Replace return(length);
with printf("%d\n", length);return(0);
and your program should work as you wish. You can test by simply running /home/hellboy632789/linelength testtestwhatever
at your bash command prompt.
Of course there are many other ways, but I suppose this is but a first step to something more complicated. Good luck and persevere.
EDIT: for example, this works:
~/316643$ cat linelength.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int length;
char *string = argv[1];
for(length = 0; string[length] != '\0'; length++);
printf("%d\n", length);
return(0);
}
~/316643$ gcc -o linelength linelength.c
~/316643$ ./linelength qwertyui
8
~/316643$ line="qwerty uiop"
~/316643$ length=`./linelength "$line"`
~/316643$ echo "length is $length bytes"
length is 8 bytes
~/316643$
EDIT 2: Bash will split everything that follows the command linelength
at the spaces, except if you protect the spaces using backslashes or enclose the strings in quotes. You have two choices for arguments with spaces, either you protect the spaces like this:
~/316643$ line="qwerty uiop"
~/316643$ ./linelength "$line"
length is 12 bytes
~/316643$
Note that this will count the spaces.
Or else you modify your C program to count all the argv[i], with i from 1 to argc-1. That will not count the spaces, so you will not know if there were several spaces between the words.
Upvotes: 1