N
nullptr
Hello group,
I am learning C using K&R2 book and as an exercise wrote grep-like
program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 100
void stdinput(char **);
char line[MAXLEN];
int lineno = 0, i = 0;
int main(int argc, char *argv[])
{
if(argc > 1)
{
if(((strcmp(argv[1], "-l")) == 0 ||
(strcmp(argv[1], "--line-number")) == 0 ))
i = 1;
if(argc >= 3 && !( i && argc == 3))
{
FILE *fp;
char **p;
if(i)
p = &argv[3];
else
p = &argv[2];
if(*p[0] == '-')
stdinput(&argv[2]), exit(EXIT_SUCCESS);
while(*p)
{
if(( fp = fopen(*p, "r")) != NULL)
{
while((fgets(line, MAXLEN, fp)) != NULL) {
if(i)
{
if(strstr(line, argv[2]) != NULL)
{
printf("%s:%d: ", *p, lineno);
printf("%s", line);
}
}
else
if(strstr(line, argv[1]) != NULL)
printf("%s", line);
lineno++;
}
fclose(fp);
}
else
fprintf(stderr, "Can't open filename %s.\n", *p);
++p;
}
}
else
stdinput(&argv[2]);
}
else
printf("grep v0.2\n"
"Usage: %s [OPTION]... [PATTERN] [FILE]\n" "Search the stdin/FILE
for the occurrence(s) of the PATTERN\n" "\nAvailable options:\n"
" -l, --line-number print the line number for the
matching lines\n", *argv);
return 0;
}
void stdinput(char **p)
{
while( (fgets(line, MAXLEN, stdin)) != NULL) {
lineno++;
if(i)
{
if(strstr(line, *p) != NULL)
{
printf("%d: ", lineno);
printf("%s", line);
}
}
else
if(strstr(line, *p-1) != NULL)
printf("%s", line);
}
}
Any suggestions, correction, comments appreciated. --
nullptr
I am learning C using K&R2 book and as an exercise wrote grep-like
program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 100
void stdinput(char **);
char line[MAXLEN];
int lineno = 0, i = 0;
int main(int argc, char *argv[])
{
if(argc > 1)
{
if(((strcmp(argv[1], "-l")) == 0 ||
(strcmp(argv[1], "--line-number")) == 0 ))
i = 1;
if(argc >= 3 && !( i && argc == 3))
{
FILE *fp;
char **p;
if(i)
p = &argv[3];
else
p = &argv[2];
if(*p[0] == '-')
stdinput(&argv[2]), exit(EXIT_SUCCESS);
while(*p)
{
if(( fp = fopen(*p, "r")) != NULL)
{
while((fgets(line, MAXLEN, fp)) != NULL) {
if(i)
{
if(strstr(line, argv[2]) != NULL)
{
printf("%s:%d: ", *p, lineno);
printf("%s", line);
}
}
else
if(strstr(line, argv[1]) != NULL)
printf("%s", line);
lineno++;
}
fclose(fp);
}
else
fprintf(stderr, "Can't open filename %s.\n", *p);
++p;
}
}
else
stdinput(&argv[2]);
}
else
printf("grep v0.2\n"
"Usage: %s [OPTION]... [PATTERN] [FILE]\n" "Search the stdin/FILE
for the occurrence(s) of the PATTERN\n" "\nAvailable options:\n"
" -l, --line-number print the line number for the
matching lines\n", *argv);
return 0;
}
void stdinput(char **p)
{
while( (fgets(line, MAXLEN, stdin)) != NULL) {
lineno++;
if(i)
{
if(strstr(line, *p) != NULL)
{
printf("%d: ", lineno);
printf("%s", line);
}
}
else
if(strstr(line, *p-1) != NULL)
printf("%s", line);
}
}
Any suggestions, correction, comments appreciated. --
nullptr