Вы находитесь на странице: 1из 39

 WRITE A SHELL PROGRAM TO CHECK THE GIVEN STRING

IS PALINDROME OR NOT.

l=0

Cnt=l

Tag=0

Echo “ Enter a string ?”

Read str

1= ‘echo $ str/wc-c

l= ‘expr $ ½’

while [ $ cnt- le $ lh ]

do

c1 = ‘echo $ str/cut-c $ cnt’

c2 = ‘echo $ str/cut-c $ 1’

if [ $ cl ! = $ c2]

then

cut = $lh

tag = l

fi

cnt = ‘ expr scnt +1’

= ‘ expr $ 1-1”

Done

If [ $ tag - ego]
Then

Echo “ string is palindrome”

Else

Echo “ string is not palindrome”

fi
OUTPUT:
 WRITE A SHELL PROGRAM TO FIND FACTORIAL.

echo "Enter a number"

read num

fact=1

n=$num

while [ $num -ge 1 ]

do

fact=`echo $fact \* $num|bc`

let num--

done

echo "factorial of $n is $fact"

OUTPUT:
 WRITE A SHELL PROGRAM TO FIND BIGGEST AMONG
THREE NUMBERS.
Echo “Enter A value:”

Read a

Echo “Enter B value:”

Read b

Echo “Enter C value:”

Read c

If [$a-gt $b] && [$a-gt $c]

Then

Echo “ A value is greater”

Elif [$b-gt $a] && [$b-gt $c]

Then

Echo “ B value is greater”

Else

Echo “ C value is greater”

fi
OUTPUT:
 IMPLEMENTATION OF LINK AND UNLINK IN C.

#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>

#define LOCKFILE "/etc/ptmp"


#define PASSWDFILE "/etc/passwd"
#define SAVEFILE "/etc/opasswd"
...
/* If no change was made, assume error and leave passwd unchanged. */
if (!valid_change) {
fprintf(stderr, "Could not change password for user %s\n", user);
unlink(LOCKFILE);
exit(1);
}

/* Change permissions on new password file. */


chmod(LOCKFILE, S_IRUSR | S_IRGRP | S_IROTH);

/* Remove saved password file. */


unlink(SAVEFILE);

/* Save current password file. */


link(PASSWDFILE, SAVEFILE);

/* Remove current password file. */


unlink(PASSWDFILE);

/* Save new password file as current password file. */


link(LOCKFILE,PASSWDFILE);

/* Remove lock file. */


unlink(LOCKFILE);

exit(0);
 STUDY ABOUT THE GENERAL PURPOSE UTILITIES :-
(A) BANNER
(B) CAL
(C) DATE
(D) TTY
(E) BC
(F) SPELL AND FSPELL

(A) BANNER :-

The Unix banner program outputs a large ASCII art version of the text that is
supplied to it as its program arguments. One use of the command is to create
highly visible separator pages for print jobs.

Implementation

The way that the program is implemented internally is error-prone and antiquated.
The character fonts used are hardwired into the program code itself, as statically
initialized data structures. Two data structures are used. The first is a data table
comprising a sequence of printing instructions that encode the bitmap for each
character (in an encoding specific to the banner program). The second is an index
into that table that indicates, for each character code, where the printing
instructions for that character begin and end.

Both data structures were hand-written. Spinellis observes that it is "difficult to


come up with a more error-prone and unmaintainable data format". He observes a
stark contrast between the source code of the banner program and automatically
generated source code for encoding computer fonts into program data (using the 6-
by-10 font data in the source code of the mac68k port of NetBSD for comparison).
The automatically generated data are commented, documenting with ASCII art
how the bit patterns were derived. The automatically generated data were
generated from a bitmap file, itself generated using a bitmap creation/editing
program with a graphical user interface. And the automatically generated data are
organized in a straightforward and obvious manner — a fixed-length sequence of
unencoded bytes for each glyph.

Spinellis further observes that in modern computer systems it is seldom sensible to


embed such data into the program executable image itself, the performance gains
of doing so being negligible. Doing so makes it difficult to adapt the program to
different locales, or to maintain the program. The more preferred approach in
modern systems is to store such data in a separate data file, distinct from the
program executable image file, or in a resource fork of the program, that the
program reads at run-time.

Operation

Each argument is truncated at 10 characters and printed on a "line" of its own. To


print multiple words on a single line, they must therefore be passed as a single
argument, which is done from the shell by escaping or quoting the words as
appropriate.

A related, and more flexible, program is figlet, which can display text in different
fonts and orientations.

SYNTAX:
$banner

(B) CAL :-

cal is a standard program on Unix and Unix-like operating systems that prints an
ASCII calendar of the given month or year. If the user does not specify any
command-line options, cal will print a calendar of the current month.

SYNTAX:

$cal

Examples

$ cal

April 2010

Su Mo Tu We Th Fr Sa

1 2 3

4 5 6 7 8 9 10

11 12 13 14 15 16 17

18 19 20 21 22 23 24

25 26 27 28 29 30

The Gregorian reformation was adopted by the Kingdom of Great Britain,


including its possessions in North America (later to become eastern USA), in
September 1752. As a result the September 1752 cal shows the adjusted days
missing. This month was the official (British) adoption of the Gregorian calendar
from the previously used Julian calendar. This has been documented in the man
pages for Sun Solaris as follows. "An unusual calendar is printed for September
1752. That is the month 11 days were skipped to make up for lack of leap year
adjustments." The Plan 9 from Bell Labs manual states: "Try cal sep 1752."

(C) DATE :-

Date" is utility to set the time and create a timestamp is user-defined format in
Unix, Linux or BSD system. It does not have the ability to convert one timestamp
representation into another but BSD variant has the ability to convert date
representation in seconds to any format you wish. there are also numerous "Unix
timestamp calculators" on the WEB. for example

Standard Time To UNIX Timestamp Calculator

4WebHelp - Online Tools Unix Timestamp Converter

It was first seen in Version 1 of AT&T Unix, circa 1969, and has both grown and
improved over the years to provide you with a wide variety of configurable options
for your system.

The most important for scripting functionality of date is the the ability to create
timestamp is wide variety of formats.

date +"%Y/%m/%d %H:%M"

The output should look something like this:

2010/01/04 06:28

If you are ok with two year year representation you can use %y instead of %Y.
There is also a macro %D that provides date in mm/dd/yy format, so we can
rewrite the previous example as

date +"%D %H:%M"

Here are most important build-in macros for date:

* %% a literal %
* %a locale's abbreviated weekday name (Sun..Sat)

* %A locale's full weekday name, variable length (Sunday..Saturday)

* %b locale's abbreviated month name (Jan..Dec)

* %B locale's full month name, variable length (January..December)

* %c locale's date and time (Sat Nov 04 12:02:33 EST 1989)

* %d day of month (01..31)

* %D date (mm/dd/yy)

* %e day of month, blank padded ( 1..31)

* %H hour (00..23)

* %j day of year (001..366)

* %m month (01..12)

* %M minute (00..59)

* %n a newline

* %p locale's AM or PM

* %r time, 12-hour (hh:mm:ss [AP]M)

* %S second (00..60)

* %t a horizontal tab

* %T time, 24-hour (hh:mm:ss)

* %U week number of year with Sunday as first day of week (00..53)

* %V week number of year with Monday as first day of week (01..52)

* %w day of week (0..6); 0 represents Sunday

* %W week number of year with Monday as first day of week (00..53)

* %x locale's date representation (mm/dd/yy)


* %X locale's time representation (%H:%M:%S)

* %y last two digits of year (00..99)

* %Y -- ccyy year

Date also can work not with the current time but with time of modification of the
referenced file

date -r /etc/passwd +"%y%m%d"

It also can serve as data calculator.

Various options for past days (GNU date only):

date +"%Y%m%d" -d sunday # GNU date

20060709

date +"%Y%m%d" -d last-sunday # GNU date

20060702

date +"%Y%m%d" -d last-week # GNU date

date -v -1m +"%Y%m%d" # BSD date

20060627

date +"%Y%m%d" -d last-month # GNU date

date -v -1w +"%Y%m%d" # BSD date

20060604

date +"%Y%m%d" -d last-year # GNU date

date -v -1y +"%Y%m%d" # BSD date

20050704

date +"%Y%m%d" -d next-week # GNU date


date -v 1w +"%Y%m%d" # BSD date

20060711

date +"%Y%m%d" -d next-month # GNU date

date -v 1m +"%Y%m%d" # BSD date

20060804

date +"%Y%m%d" -d next-year # GNU date

date -v 1y +"%Y%m%d" # BSD date

20070704

To show the time in seconds since 1970-01-01 (Unix epoch):

date +"%s" -d "Fri Apr 24 13:14:39 CDT 2009"

1240596879

To convert Unix epoch time (seconds since 1970-01-01) to a human readable


format:

date -d "UTC 1970-01-01 1240596879 secs"

Fri Apr 24 13:14:39 CDT 2009

Or:

date -ud @1000000000

Sun Sep 9 01:46:40 UTC 2001

Examples

date "+%-m/%-d/%y"

7/4/06

date "+%Y%m%d"
20060704

$ date +"%b %d, %Y"

Mar 14, 2010

date -d yesterday +"%Y/%m/%d"

2010/03/13

Yesterday assigned to variable

DATE=$(date -d yesterday +"%Y%m%d")

echo $DATE

20060704

To assign the time to a variable

START=`date '+%r'`

echo $START

03:06:02 PM

sleep 5

echo $START

03:06:02 PM

N.B. the variable has the time when it was assigned.

Yesterday assigned to variable

DATE=$(date -d yesterday +"%Y%m%d")

echo $DATE

20060704

To show the time in a different timezone, the TZ environmentvariable is read,


Timezone types is found in /usr/share/zoneinfo
OLDTZ=$TZ

export TZ=GMT; echo "GMT: `date +\"%F %R (%Z)\"`"

GMT: 2008-10-31 12:30 (GMT)

export TZ=Europe/Stockholm; echo "Stockholm: `date +\"%F %R (%Z)\"`"

Stockholm: 2008-10-31 13:30 (CET)

export TZ=Asia/Kuala_Lumpur; echo "Kuala Lumpur: `date +\"%F %R (%Z)\"`"

Kuala Lumpur: 2008-10-31 20:30 (MYT)

export TZ=US/Central; echo "Dallas: `date +\"%F %R (%Z)\"`"

Dallas: 2008-10-31 07:30 (CDT)

export TZ=$OLDTZ

Using date for offset calculation:

date +"%Y%m%d" -d sunday

20060709

date +"%Y%m%d" -d last-sunday

20060702

date +"%Y%m%d" -d last-week

20060627

date +"%Y%m%d" -d last-month

20060604

date +"%Y%m%d" -d last-year

20050704

date +"%Y%m%d" -d next-week


20060711

date +"%Y%m%d" -d next-month

20060804

date +"%Y%m%d" -d next-year

20070704

(D) TTY :-

tty is a Unix command that prints to standard output the name of the file connected
to standard input. The name of the program comes from teletypewriter, abbreviated
"TTY".

SYNTAX:

$tty

When the program runs, it will output something like this:

$ tty

/dev/pts/4

The pts indicates that it is a pseudo terminal, with the number following it. If the
program was run on a true tty, it would output something like this:

$ tty

/dev/tty2

(E)BC :-

bc is "an arbitrary precision calculator language" with syntax similar to the C


programming language. It is generally used by typing the command bc on a Unix
command prompt and entering a mathematical expression, such as (1 + 3) * 2,
whereupon 8 will be output.
There are currently two main dialects: the rigorously defined POSIX bc, and its
direct descendant, the much expanded GNU bc (also, GNU bc is available for a
wider range of platforms, such as Microsoft Windows). A more recent dialect, Plan
9 bc, is a superset of the former and subset of the latter.
All three forms of bc can be executed as either a mathematical scripting language
or as an interactive mathematical shell.
SYNTAX:
$bc
Operations
^d
1 base _input base
0 base _output base are used for base conversions.
BASE:
Decimal: 1
Binary: 2
Octal: 8
Hexadecimal: 16
POSIX bc
The POSIX standardized bc language is traditionally written as a program in the dc
programming language to provide a higher level of access to the features of the dc
language without the complexities of dc's terse syntax.
In this form, the bc language contains single letter variable, array and function
names and most standard arithmetic operators as well as the familiar control flow
constructs, (if(cond)..., while(cond)... and for(init;cond;inc)...) from C. Unlike C,
an if clause may not be followed by an else.
Functions are defined using a define keyword and values are returned from them
using a return followed by the return value in parentheses. The auto keyword
(optional in C) is used to declare a variable as local to a function.
All numbers and variable contents are arbitrary precision numbers whose precision
(in decimal places) is determined by the global scale variable.
The numeric base of input (in interactive mode), output and program constants
may be specified by setting the reserved ibase (input base) and obase (output base)
variables.
Output is generated by deliberately not assigning the result of a calculation to a
variable.
Comments may be added to bc code by use of the C /* and */ (start and end
comment) symbols.
Mathematical operators
Exactly as C
The following POSIX bc operators behave exactly like their C counterparts:
+-*/
+= -= *= /=
++ -- < >
== != <= >=
()[]{}
Similar to C
The modulus operators:
% %=
... behave exactly like their C counterparts only when the global scale variable is
set to 0, i.e. all calculations are integer-only. When scale is greater than 0 the
modulus is calculated relative to the smallest positive value greater than zero.
Only resembling C

The operators:

^ ^=

... resemble the C bitwise exclusive-or operators, but are in fact the bc integer
exponentiation operators.
'Missing' operators relative to C

The bitwise, boolean and conditional operators:

& | ^ && || ^^

&= |= ^= &&= ||= ^^=

<< >>

<<= >>=
?:

... are not available in POSIX bc.


Built-in functions

The sqrt() function for calculating square roots is POSIX bc's only built-in
mathematical function. Other functions are available in an external standard
library.
Standard library functions

bc's standard math library (defined with the -l option) contains functions for
calculating sine, cosine, arctangent, natural logarithm, the exponential function and
the two parameter Bessel function J. Most standard mathematical functions
(including the other inverse trigonometric functions) can be constructed using
these. See external links for implementations of many other functions.

Please, note that the scale changes with the -l option to 20 (source). So things such
as modulo may work unexpectedly. For example, write "bc -l" and then the
command "print 3%2" outputs 0, instead of 1. But if you do it like "bc -l",
"scale=0" and then the command "print 3%2" has 1 as output.
Plan 9 bc

Plan 9 bc is just like POSIX bc but for an additional print statement.


GNU bc

GNU bc derives from the POSIX standard and includes many enhancements. It is
entirely separate from dc-based implementations of the POSIX standard and is
instead written in C. Nevertheless, it is fully backwards compatible as all POSIX
bc programs will run unmodified as GNU bc programs.

GNU bc variables, arrays and function names may contain more than one
character, some more operators have been included from C, and notably, an if
clause may be followed by an else.
Output is achieved either by deliberately not assigning a result of a calculation to a
variable (the POSIX way) or by using the added print statement.

Furthermore, a read statement allows the interactive input of a number into a


running calculation.

In addition to C-style comments, a # character will cause everything after it until


the next new-line to be ignored.

The value of the last calculation is always stored within the additional built-in last
variable.
Extra operators

The following logical operators are additional to those in POSIX bc:

&& || !

... and are available for use in conditional statements (such as within an if
statement). Note, however, that there are still no equivalent bitwise or assignment
operations.
Functions

All functions available in GNU bc are inherited from POSIX. No further functions
are provided as standard with the GNU distribution.

(F)SPELL AND FSPELL :-


One of the characteristics of the English written language is that its orthography
(i.e., spelling) is complex and can be difficult to remember. This is in contrast to
many languages (e.g., Spanish and German) for which the spelling of words is
closely related to their pronunciation. Fortunately, technology has come to the
rescue, and there are multiple ways to check and correct spelling on Linux and
other Unix-like operating systems.

One of the simplest, and sometimes most convenient, of these spelling checkers is
the spell command. Despite its lack of sophisticated features, it is still worth being
aware of spell for several reasons, including (1) it is very easy to use, (2) it can be
found on many Unix-like systems and (3) it is well suited for use with other
commands linked by pipes (which are used to combine commands).

spell compares words typed in at the keyboard or the contents of a text file to those
in a built-in dictionary file and then writes all of the words not in the dictionary
(and, therefore, presumably misspelled) to standard output (which is the display
screen by default).

On some systems spell is a stand-alone program, either the original version or the
GNU clone. On others, such as Red Hat Linux 9, it is a shell script (i.e., a simple
program) that launches a simplified version of another spelling checking program,
aspell, which emulates the core function of spell.

spell displays each presumably misspelled word on a new line. In the case of the
Red Hat version, the words are displayed in alphabetic order and each erroneous
spelling is displayed only once, regardless of the number of times that it appears in
the text. If multiple files are specified for checking, a single, alphabetized list of
words is still generated.

spell's syntax is

spell [options] [file_name(s)]


The items in the square brackets are optional. When no file names are supplied as
arguments (i.e., inputs), spell will read from standard input, which by default is
text typed in at the command line.

For example, it can easily be determined whether the word desireable is spelled
correctly by first entering at the command line the spell command, pressing the
RETURN key, typing the word desireable, pressing RETURN again and then
simultaneously press the CONTROL key and the d key. The output will look like
the following:

$ spell
desireable
desireable
$

The word desireable is echoed (i.e., repeated by the system) because it is not in the
system dictionary and is thus quite likely a spelling error. If the same procedure is
repeated using desirable (i.e., omitting the second e), then it is not echoed, because
it is in the system dictionary and is therefore the correct spelling. Thus, the screen
would look like:

$ spell
desirable
$

spell can also be used with lists of words and sentences. For example, typing spell,
pressing the RETURN key, typing the sentence This is the storry abuot an
operating system that went from baad to wurse, pressing RETURN again, and
finally simultaneously pressing the CONTROL key and the d key would produce
the following output:

$ spell
This is the storry abuot an operating system that went from baad to wurse
abuot
baad
storry
wurse
$

To find any spelling errors in a file, all that is necessary to supply the name of the
file as an argument after the command and any options. For example, the following
will search for errors in a file named file1:

spell file1

spell can be used to check any number of files simultaneously by listing them all as
arguments, for example:

spell file1 file2 file3

It is then a simple matter to correct the misspellings using a text editor (e.g., vi or
gedit).

As is the case with other filters, the output of spell can be redirected from standard
output using the standard output redirection operator, which is designated by a
rightward facing angular bracket. For example, the following tells spell to check
the spelling of all words in the first three files and write its output to file4 instead
of to the display screen:

spell file1 file2 file3 > file4

The output of spell can also be further processed by using pipes to send it to other
filters. For example, in the following example the output of spell is piped to grep
(which is used to search for files and the contents of files) in order to display only
those misspelled words in file5 that contain the sequence of letters com

spell file5 | grep com

The output could likewise be redirected to a file instead of to the display screen,
such as to a new or existing file named file6:
spell file5 | grep com > file6

Although spell is very useful for checking text against the several tens of thousands
of commonly used words in the English language that are included in the
dictionary file, it does not do a good job of checking technical terminology, proper
nouns (e.g., names of people, places and products) and slang.

Also, spell is not interactive. That is, it does not highlight misspelled words in a
file and assist the user in correcting them one by one in the context of the text.
However, this can be an advantage in some cases, particularly if the user merely
wants to see a list of the potentially misspelled words in a file without having to go
through and attempt to correct all of them.

Moreover, some of the useful features that come with the original version of spell
are not found on the aspell emulation version. For example, the original Unix
version has several options, including -b, which accepts UK spellings (e.g. labour,
colour, centre), and -x, which displays every possible stem for each word. The
original version also allows users to create their own supplementary dictionary
files, which can be very useful for adding technical terms and proper nouns.

When more features are desired for a command line spelling checker than are
available on the the aspell emulation version, the user should consider installing
the original version of spell or its GNU clone or using a more sophisticated
program such as aspell or ispell, both of which are interactive and allow the use of
user-created dictionaries. aspell is better at making suggestions when a word is
seriously misspelled, whereas ispell has the advantage that it can be used with
numerous foreign languages.

This article was written using the gedit text editor on a Red Hat 9 Linux machine.
spell was used to check the spelling after the final proofreading by the author, and
it found several errors. Interestingly, the only word that was misspelled multiple
times was the word misspell itself, which was spelled mispell.
 IMPLEMENTATION OF GREP COMMAND IN C.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

/* calculate filesize */
int calc_bufsize(char *filename)
{
struct stat st;

stat(filename, &st);
return ((int)st.st_size);
}

int main(int argc, char *argv[])


{
if(argc < 3)
{
printf("Usage:\n\t%s <word> <files> ...\n", argv[0]);
return -1;
}

FILE *fp;
char *filename;
int x = 2;

/* process each file */


for(x; x != argc; x++)
{
filename = argv[x];

if( (fp = fopen(filename, "r")) == NULL)


{
printf("Failed to open file: %s\n", argv[2]);
return -2;
}

int BUFSIZE = calc_bufsize(filename);

/* read ENTIRE file into buf[] */


char buf[BUFSIZE];
fread(&buf, sizeof(char), BUFSIZE, fp);

/* search buf for word (case sensitive) */


char *ans = strstr(buf, argv[1]);

/* word found, print filename */


if(ans != NULL)
printf("%s\n", filename);

/* word not found, do nothing */


fclose(fp);
}
return 0;
}

 IMPLEMENTATION OF WE COMMAND IN C.

/*count.c : Count characters in a file*/


#include <stdio.h>
#include<process.h>

void main()
/* Prompt user for file and count number of characters
and lines in it*/
{
FILE *fopen(), *fp;
int c , nc, nlines;
char filename[40] ;
nlines = 0 ;
nc = 0;

printf("Enter file name: ");


gets( filename );

fp = fopen( filename, "r" );

if ( fp == NULL )
{
printf("Cannot open %s for reading \n", filename );
exit(1); /* terminate program */
}

c = getc( fp ) ;
while ( c != EOF )
{
if ( c == '\n' )
nlines++ ;

nc++ ;
c = getc ( fp );
}

fclose( fp );
if ( nc != 0 )
{
printf("There are %d characters in %s \n", nc, filename );
printf("There are %d lines \n", nlines );
}
else
printf("File: %s is empty \n", filename );
}

 IMPLEMENTATION OF MORE COMMAND IN C.

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
FILE *fopen(),*fp;
int c,count=1,count2=1;
char file_name[50];
printf("Enter The file name :");
gets(file_name);
fp=fopen(file_name,"r");
if ( fp == NULL )
{
printf("Cannot open %s for reading \n", file_name );
exit(1); /* terminate program */
}

c=getc(fp);
while(c!=EOF)
{
if(c=='\n')
count++;
c=getc(fp);
}
fclose(fp);

fp=fopen(file_name,"r");
c=getc(fp);
while(c!=EOF)
{
if(c=='\n')
count2++;
if(count2%49==0)
{
per=(count2/count)*100;
printf("--MORE--%d%",per);
}
c=getc(fp);
}
fclose(fp);
}

 IMPLEMENTATION OF LS COMMAND IN C.

#include<iostream.h>
#include<sys/types.h>
#include<direct.h>
#include<stdlib.h>

int main(int argc, char *argv[])


{
int i;
DIR*dp;
struct direct*dirp;

if (argc==2)
{
dp = opendir(argv[1]);
while ((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d-name);
}
else
{
if (argc == 1)
{
dp = opendir(".");
while ( (dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d-name);
}
else
{
printf("ls - Error - too many parameters\n");
exit(0);
}

};
closedir(dp);
return 0;
}

Output
INDEX

S.No Practical Questions Date Remarks


1. Installation of unix & linux

2. Study about general purpose


utilities:
(1) Banner
(2) Cal
(3) Date
(4) Tty
(5) Bc
(6) Spell and fspell
3. Implementation of WE command
in C
4. Implementation of Grep
command in C
5. Implementation of More
command in C
6. Implementation of Link and
Unlink command in C
7. Implementation of LS command
in C
8. Study about unix system variables
9. Write the shell program to find
biggest among three numbers.
10. Write a shell program to find
factorial.
11. Write a shell program to check the
given string is palindrome or not.
 IMPLEMENTATION OF GREP COMMAND IN C

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

/* calculate filesize */
int calc_bufsize(char *filename)
{
struct stat st;
stat(filename, &st);
return ((int)st.st_size);
}

int main(int argc, char *argv[])


{
if(argc < 3)
{
printf("Usage:\n\t%s <word> <files> ...\n", argv[0]);
return -1;
}

FILE *fp;
char *filename;
int x = 2;

/* process each file */


for(x; x != argc; x++)
{
filename = argv[x];

if( (fp = fopen(filename, "r")) == NULL)


{
printf("Failed to open file: %s\n", argv[2]);
return -2;
}

int BUFSIZE = calc_bufsize(filename);

/* read ENTIRE file into buf[] */


char buf[BUFSIZE];
fread(&buf, sizeof(char), BUFSIZE, fp);

/* search buf for word (case sensitive) */


char *ans = strstr(buf, argv[1]);

/* word found, print filename */


if(ans != NULL)
printf("%s\n", filename);

/* word not found, do nothing */

fclose(fp);
}
return 0;
}

Вам также может понравиться