Searching a simple text pattern in the command line arguments program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: Run at command prompt
To do: Searching a simple text pattern in the command line arguments program example
To show: How to create a console C program which accept the command line arguments
// searchpattern.cpp, working program
#include <stdio.h>
#include <string.h>
#define MAXLINE 100
int getline(char *line, int max)
{
int count, i;
i=0;
while(--max > 0 && (count=getchar()) != EOF && count != '\n')
line[i++] = count;
if(count=='\n')
line[i++] = count;
line[i]='\0';
return i;
}
// find and print lines that match the
// pattern from the 1st argument
main(int argc, char *argv[])
{
char line[MAXLINE];
int found = 0;
// If just program name (argc = 1), then...
if(argc != 2)
printf("Usage: searchpattern thepattern\n");
// If the program name with switch/option (argc = 2), then...
else
while(getline(line, MAXLINE) > 0)
{
if(strstr(line, argv[1]) != NULL)
{
printf("%s", line);
found++;
}
}
return found;
}
Output example:
(This program run at the command prompt)
F:\vc2005project\searchpattern\debug>searchpattern
Usage: searchpattern thepattern
F:\vc2005project\searchpattern\debug>searchpattern somepattern
Test the somepattern word
Test the somepattern word
No 'somepattern' here?
No 'somepattern' here?
If there are somepattern word, it will print it out
If there are somepattern word, it will print it out
else, the program just ignore your input like this line
Can you see the somepattern word printed?
Can you see the somepattern word printed?
^Z
F:\vc2005project\searchpattern\debug>