Reputation: 103
I'm quite new to Linux and not familiar with C. Here I have one question about both.
I'm writing a C program to run in Linux. And I have a file names f.txt in the same folder. With some fields like this:
Jason 12 Male
I want to compare the $2 of the txt file of each line with the value of parameter a. If the second field of the line is greater than a, then print the first field $1.
I tried codes like this but not work. Can anybody help? Thanks!
void main()
{ int a;
scanf("%d",&a);
char* comm="awk '{if($2>"+a+") print $1}' f.txt";
system(comm);
}
Upvotes: 1
Views: 95
Reputation: 70502
For your stated problem, which is just basic text file processing, it is probably easiest to solve this task using a scripting language itself, rather than using C (such as python, perl, or awk itself).
For your programming problem, the C language does not support that kind of string concatenation. You have to build the string using a call to snprintf()
(or via calls to strcat()
).
char comm[512];
int r = snprintf(comm, sizeof(comm), "awk '{if($2>%d) print $1}' f.txt", a);
if (r < 0) {
/* error */
} else if (r < sizeof(comm)) {
/* ok */
} else {
/* need a bigger comm buffer... */
}
Upvotes: 2
Reputation: 3761
An alternative approach to handling this problem would be the following: Read the bytes from stdin with the following snippet:
while ( ( char *data = scanf( "%s %d %s\n" ) ) != EOF )
... where the newline is your delimiter. Then you can perform the appropriate actions on "data" to access each field individually.
It would be ran by piping your text file to the program:
./program < textfile.txt
Upvotes: 1