Professional Documents
Culture Documents
haracter Arrays
nd Strings
INTRODUCTION
i sSsequence
a of characters that is treated as a single
data item. We have used
c in a number of examples in the past. Any group of characters (except double quote
defined between double quotation marks is a string constant. Example:
"Man is obviously made to think."
liwe want to include a double quote in the string to be printed, then we may use it with a
slash as shown below.
" Man is obviously made to think," said Pascal."
Texample,
printf ("\" Wel1 Done "\");
output the string
Well Done!"
Ple the statement
Done ");
printf(" Well
Output the string
Well Done! and readable programs.
The com-
meaningful
aracter strings are often used to build
include:
Peratinngs
operations performed on character
strings
The size determines the number of characters in the string_namej Some examplesarea
char city[10];:
char name [30];
When the compiler assigns a character string to a character array, it automatical
plies a null character ('10 ) at the end of the string. Therefore, the size should be equalte
maximum number of characters in the string plus one.
Like numeric arrays, character arrays may be initialized when they are declared. (y
mits a character array to be initialized in either of the following two forms:
char city [9] NEMH YORK"
=
"
GOOD" in it, terminates with the null character, and initializu3 all other elemene
The storage will look like:
Goo D10 10 10 o 10 10
However, the tollowing
declaration is illegal
char str2[3] "G00D"
TERMINAL
FROM
READING STRINGS
read in a
lsing s c a n l F u n c t i o n
format specification to
cs
be used with
function s c a n f
can
.e Lamiliar input
Example:
g of characters.
char add ress[10]
scanf("ss", address) ; e it
is that it terminates its input on the first white space
roblem with the scanf function tabs. carringe returns,
form feeds, and new lines.
Functions
Using getchar and gets character from the term
how to read a single
Chapter 4 as to read successive si
We have discussed in We can use this function repeatedly to an entire
the functie getehar.
them into a
eharacter array.
Thus, line ofCha
text hara
ean be
ters from the input and place when the newline character
The reading is terminated
read and stored in an array.
inserted at the end of the
string. The geto
character is then
entered and the null
tion call takes the form:
char ch; t\u
Tvd U
ch getchar ();
c++
= character;
while(character != 'In');
cC 1;
1ine[c]='\0';
printf("\n&s\n", 1line);
Fig.8.2 Frogram to redd a line
of text from terminal
nf. it does not skip whitespaces. For example the code segment
char 1ine [80]
gets (1ine)
printf (*s", line)
e of text from the keyboard and displays it on the screen. The last two statements
bined as follows:
printf("s", gets(1ine));
not to input more character that can be stored in the string variable used. Since C
check array-bounds, it may cause
problems.)
notprovide operators that work on strings directly. For instance we cannot
g1o another assign
directly. For example, the assignment statements.
string "ABC";
valid. If we string1 =string2;
really want to copy the characters in string2 into
arader-by-character basis. stringl, we may do so
oe .3 Write a
we progre copied.
program
of characters
to copy one
string into another and count the number
ram is shown
into
into thewn in Fig. 8.3. We use a for
ke loop to copy the characters contained inside
are
againstring1. The loop is
assigning a null minated when the null character is reached. Note
character to the stringl
236 Programming in ANSI C
Program
main)
C)-sli) printf("\n"); w
printf("%s\n", stringl);
printf("Number of characters =
$d\n".
Totau
Sa utput
nter a string
?Manchester
ts
shi
Manchester
e p f f poute
FILE s7
AE data
ws we tyhe-stdio h
wh rulos
12
ile Marnagement
inC
2 INTRODUCTION
now we have been using the functions such as scanf and printf to read and
are console oriented lO functions, which always use the terminal (keyboarddata.
write
and
en) as the target place. This works fine as long as the data is small. However, many real-
problems involve large volumes of data and in such situations, the console oriented IO
rations pose two major problems.
It
becomes cumbersome and time consuming to handle large volumes of data through
terminals.
Iheentire data is lost when either the program is terminated or the computer is
turned off.
8therefore necessary to have a more flexible approach where data can be stored on the
and read whenever necessary, without destroying the data. This method employs the
eptof files to store data. A file is a place on the disk where a group of related data is
red a number of functions that have the ability to
d Like most
basic file
m
other languages,C supports
operations, which include:
naming a file,
opening a file,
'reading data fronm a file,
writing data to a file, and
closing a file.
ere are file operations is known as the
in C. The first one
and uses UNIX System calls. The shall discuss in this chapter
peration
npor nd uses functions in C's standard
I/O library. We
are available
that
in the C library. They listed
l i in
are
121
le handling functions
ANSI C
Programming in
390
Level I/O Functions
Table 12.1 High
Function name
Operation
Creates a new file for use.
fopen) *Opens an existing
file for use.
subsequently used as
used as a
ntains all the
a
he
pointer, w h i c h co information is subsequently
about the efile 1s
e
pens
terk hetween
the system and the program. this
The
the purpose of opening this file.T mode does
etatementthe
also specifies
i o nl i n k ,
Thes e c o n d
be
one of the fol
following:
can
Mode for reading only.
b the file
open
the file
for writing only.
w
o p e n
D the file
for appending (or adding) data to it.
ope in
be enclosed
that
both
the f ename and mode are specified as strings. They should
dN
o uo
b lteequotation marks,
ble
When
quorying to open a file, one of the following things may happen:
not
if the file does
mode is 'writing, a file with the specified n a m e is created
Whe hen the
The c o n t e n t s are deleted,
if the file already exists.
contents safe. A
is "appending, the file is opened with the current
exist.
This would close the file associated with the FILE pointer filepointer. Look
ok at
at the
the fo
lowing segment of a program.
FILE P NPUT"
p2 fopen ("OUTPUT", "");
fclose (p1);
fclose(p2);
This program opens two files and closes them after all operations on them are comnleted
Once a file is closed, its file pointer can be reused for another file. ted
As a matter of fact all files are closed automatically whenever a program terminatea
However, closing a file as soon as you are done withit is a good programming habit.
A program and the related input and output data are shown
in Fig. 12.1. We enter the T
data via the keyboard and the program writes it, character by
character, to the file IN the
The end of the data is indicated by entering an EOF character, which is
control-
reference system. (This may be control-D in other systems.) The file INPUT is closed a this
signal
File 393
Managunet in C
<Stdio.h
se(f1);
nData Outputin\n");:
Reopen the file INPUT
fopen("INPUT",'r*);
input
program to test the file handling
tures on this
systemZ
Dutput
is
rogram to test the file handi ing
r
res on this system
putw(integer, fp);
getw(fp):
Example 12.2 illustrates the use of putw and getw functions.
end-of-file mark.
reads value, assigns the same to number, and then tests for the
a
Finally, the program displays the contents of ODD and EVEN files.
It is important
to
note
reopened
that the files ODD and EVEN opened for writing are closed before they
are
reading.
Program
#include <stdio.h>
main()