fgrep.c
来自「C语言编写的关于文件的基本 操作的程序源代码」· C语言 代码 · 共 65 行
C
65 行
/*-----------------------------------------------------
Something important :
char *fgets(char *buffer,int buffer_size,FILE *stream);
fgets read chars from the stream, and then copy it to
the buffer, It will stop when the '\n' be found, and it
will stop when the size of the string is [sizeof(buf)-1]
too.In any case, the data will keep till next call of
fgets.
fgets will start read chars from what lasted last time,
In any case, a '\0' will push into the buffer, so the
result of it will be a string : end by '\0'.
-------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 512
void search(char *filename,FILE *stream,char *string)
{
char buffer[BUFSIZE];
while(fgets(buffer,BUFSIZE,stream) != NULL)
{
if(strstr(buffer,string) != NULL)
{
if(filename != NULL)
printf("%s : ",filename);
fputs(buffer,stdout);
}
}
}
int main(int argc,char **argv)
{
char *string;
FILE *stream;
if(argc <= 1)
{
fprintf(stderr,"Usage : fgerp string file ... \n");
exit(EXIT_FAILURE);
}
string = *++argv;
if(argc <= 2)
search(NULL,stdin,string);
else
{
while(*++argv != NULL)
{
stream = fopen(*argv,"r");
if(stream == NULL)
perror(*argv);
else
{
search(*argv,stream,string);
fclose(stream);
}
}
}
return EXIT_SUCCESS;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?