/**
C primer plus 6th ch13
5.编写一个程序,接受两个命令行参数。第1个参数是字符,第2个参数
是文件名。要求该程序只打印文件中包含给定字符的那些行。
注意
C程序根据'\n'识别文件中的行。假设所有行都不超过256个字符,你可
能会想到用fgets()。
**/
#include <stdio.h>
#include <stdlib.h> //exit()
#include <string.h> //strchr()
#define LINE_SIZE 256
int main(int argc, char* argv[])
{
FILE* fp;
char line[LINE_SIZE];
if(argc < 3)
{
printf("Usage: %s char filename:\n", argv[0]);
exit(EXIT_FAILURE);
}
if((fp = fopen(argv[2], "r")) == NULL)
{
fprintf(stderr, "can`t open file %s.\n", argv[2]);
exit(EXIT_FAILURE);
}
printf("lines containing '%c':\n", *(argv[1]));
while(fgets(line, LINE_SIZE, fp))
{
if(strchr(line, *(argv[1])))
{
//printf("%s", line); // fgets() contain '\n'
fputs(line, stdout); //puts()会添加一个换行符,fputs()不会
}
}
if(ferror(fp))
{
fprintf(stderr, "read file %s error.]n", argv[2]);
exit(EXIT_FAILURE);
}
if(fclose(fp))
{
fprintf(stderr, "can`t close file %s.\n", argv[2]);
exit(EXIT_FAILURE);
}
return 0;
}
关于stdin/stdout/stderr
13.2.6 指向标准文件的指针
stdio.h头文件把3个文件指针与3个标准文件相关联,C程序会自动打开这3个标准文件。如表13.2所示:
这些文件指针都是指向FILE的指针,所以它们可用作标准I/O函数的参数,如fclose(fp)中的fp。
stdin: 键盘输入都会存到该文件中
stdout/stderr:写入该文件的内容,同时会在显示器上打印