命令行参数和使用C读取文件/打印文本 [英] Command line arguments and read file/print text in C
问题描述
我想用命令行参数的工作和解析C.一个文本文件基本上,我希望能够把两个数字一样,1和4,并把它读取文本文件的一列,然后打印出来到标准输出。我希望能够做这样的事情借此:
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
和做的:
./your_prog 1 4 < data.txt
PID CMD
449 bash
1129 -bash
25605 vi
6132 -bash
6208 vi
所以我需要输入我想打印出来,在重定向的data.txt文件并把它处理文件和打印像这样的列。
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.
到目前为止,我有这对我的code:
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;
}
但我不知道如果我是正确的轨道上,并很困惑,下一步该怎么做。我是新来的C,所以我道歉,如果这是一个简单的问题。
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.
推荐答案
为您开始,这可以提高你收集的命令行信息的方式。注意第一个参数的argv [0]
是可执行文件本身的名称。熊上面记的意见,我也没有提高任何进一步。语法是的progname名COL1 COL2
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 is progname filename col1 col2
#include <stdio.h>
#include <stdlib.h>
void fatal(char *msg) {
printf("%s\n", msg);
exit (1);
}
int main(int argc, char*argv[])
{
int col1, col2;
FILE *fp;
char ch[256];
if(argc < 4)
fatal("Need three arguments");
if (sscanf(argv[2], "%d", &col1) != 1)
fatal("Argument 1 error");
if (sscanf(argv[3], "%d", &col2) != 1)
fatal("Argument 2 error");
printf("Read columns %d and %d from file %s\n", col1, col2, argv[1]);
if ((fp = fopen(argv[1], "r")) == NULL)
fatal("Unable to open file");
// process the file
while (fgets(ch, 256, fp) != NULL) {
printf("%s", ch);
}
fclose(fp);
return 0;
}
这篇关于命令行参数和使用C读取文件/打印文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!