I am trying to work with command line arguments and parsing a text file in C. Basically I want to be able to put in two numbers, like, 1 and 4 and have it read a column of a text file then print it to stdout. I want to be able to do something like take this:
PID TTY TIME CMD
449 ttys000 0:00.35 -bash
1129 ttys001 0:00.35 -bash
25605 ttys001 0:00.15 vi prog.c
6132 ttys002 0:00.11 -bash
6208 ttys002 0:00.03 vi test
And do:
./your_prog 1 4 < data.txt
PID CMD
449 bash
1129 -bash
25605 vi
6132 -bash
6208 vi
So I need to enter the the columns i want to print out, redirect the file in "data.txt" and have it process the file and print like so.
So far I have this for my code:
#include <stdio.h>
int main(int argc, char **argv){
//int row = argc[0];
//int col = argc[1];
//if number entered is less than one, re-enter
int i;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
if(argc < 1){
fprintf(stderr, "Enter a valid input");
//quit
return 1;
}
else{
char ch[256];
//ch[255] = '\0';
while(fgets(ch, 256, stdin) != NULL){
printf("%s", ch);
}
}
return 1;
}
but am not sure if I am on the correct track and am confused as to what to do next. I am new to C, so I apologize if this is an easy question.
Here is what I have so far. I can get it to parse apart then I can put it back how it was, but for the life of me I cant figure out how to tell it to print only the first column. If I could have some direction, then I could figure out how to do the rest, but I can find anything. Here is what code I have so far:
To get you started, this improves the way you gather the command line information. Note the first argument
argv[0]
is the name of the executable itself. Bear in mind comments above, I haven't improved any further. Syntax isprogname filename col1 col2