Computer Programming I
UP ITTC
AY 2009-2010
Command-Line Arguments
Lesson 7
Introduction
Command-line arguments
Command-line Arguments
In environments that support C,
there is a way to pass command-line
arguments or parameters to a
program when it begins executing.
When main is called, it is called with
two arguments.
Command-line Arguments
The first (conventionally called argc, for
argument count) is the number of
command-line arguments the program
was invoked with.
The second (argv, for argument vector) is
a pointer to an array of character strings
that contain the arguments, one per
string.
Command-line arguments
Example:
/*program echo.c*/
int main( int argc, char* argv[] )
{
int i;
for( i = 1; i < argc; i++ ){
printf(“arg#%d = %s\n”, i, argv[i]);
}
}/*end of main*/
Command-line arguments
Calling the progam:
C:\ echo.out hello world
By convention, argv[0] is the name by which
the program was invoked, so argc is at least 1.
Lesson Review
You can pass data directly to your program
through the use of command-line arguments.
The main method has the following
declaration, where argc holds the number of
arguments to the program and argv points to
an array of character strings which holds the
arguments.
int main( int argc, char* argv[] )
Exercise 11
Write a program that outputs to
screen the number of times the
string “hello” was used as a
command-line argument in the
execution of the program.
Structures
Lesson 8
Introduction
Structures
Declaring structures using typedef
Pointers to Structures
Structures
A structure in C is a collection of one or more
variables, possibly of different types, grouped
together under a single name for convenient
handling. A structure is also called a record. The
syntax for declaring a structure is as follows:
struct <struct_type_name>
{
<data_type_1> <var_name_1>;
<data_type_2> <var_name_2>;
……
<data_type_n> <var_name_n>;
} <struct_name>;
Structures
Example:
struct appInfoType
{
char name[50];
char address[50];
int age;
float weight;
char telNo[10];
} appInfo;
Structures
Each item in the structure is called a
field. By definition, fields are the
related items that compose a
record.
The fields of a record is accessed by
using the following syntax:
<structure_name>.<field_name
>
Structures
Example:
strcpy(appInfo.name, "John
Smith");
strcpy(appInfo.address, "New
York City");
appInfo.age = 21;
weight = appInfo.weight;
height = appInfo.height;
Structures
To define a structure type using
typedef, the following syntax is used:
typedef struct
{
<data_type_1> <var_name_1>;
<data_type_2> <var_name_2>;
……
<data_type_n> <var_name_n>;
} <type_name>;
Pointers to Structures
Structure pointers are just like pointers
to ordinary variables. The declaration
struct appInfoType *p;
says that p is a pointer to a structure of
type struct appInfoType. If p points to an
appInfoType structure, then *p is the
structure and (*p).name and (*p).address
are some of the fields.
Pointers to Structures
Pointers to structures are so frequently
used that an alternative notation is
provided as a shorthand. If p is a pointer to
a structure, then
p -> <field_name> /* equivalent to
*(p).<field_name> */
Lesson Review
A structure in C is a collection of one or more
variables, possibly of different types, grouped
together under a single name for convenient
handling. A structure is also called a record.
Each item in the structure is called a field. By
definition, fields are the related items that compose a
record.
Pointers to structures are so frequently used that an
alternative notation is provided as a shorthand. If p is
a pointer to a structure, then
p -> <field_name> /* equivalent to
*(p).<field_name> */
Exercise 12
Define a structure to use that encompasses a student
record, as it may be kept at a school registrar. To keep
the structure simple, assume that the record holds the
surname, first name, address and general weighted
average of the student. The surname and first name
are no longer than 15 characters each, the address is no
longer than 80 characters, and the weighted average is
a value between 0 and 100 that is not necessarily an
integer.
Exercise 13
Write a program that asks the user to
input his or her first name, surname,
address and GWA to store it in a
variable of the structure defined in
the previous problem.
Dynamic Memory Allocation
Lesson 9
Introduction
Allocate space using
calloc
malloc
Freeing space
Dynamic Memory
Allocation
calloc() and malloc() are predefined
functions in C that allows us to
dynamically create space for arrays
and structures.
At runtime, we can allocate a
particular amount of space using
these functions.
calloc()
calloc() stands for contiguous allocation
SYNTAX:
calloc(<numOfCells>, <bytesPerCell>)
where
<numOfCells> is an unsigned int and it refers to the
number of cells to be allocated, and
<bytesPerCell> is an unsigned int that refers to the
number of bytes allocated for each cell.
malloc()
malloc() stands for memory
allocation
Syntax:
malloc(<totalBytes>)
where
<totalBytes> is an unsigned int that refers
to the total number of bytes to be allocated
for an array.
Freeing space
Space dynamically allocated (i.e., at
runtime) with calloc() or malloc() does not
get returned to the system upon function
exit. Programmer must use free() to
explicitly return space.
Syntax:
free(<ptr>);
where
<ptr> is a pointer dynamically allocated array.
Lesson Review
calloc() and malloc() are predefined functions
in C that allows us to dynamically create
space for arrays and structures.
calloc() stands for contiguous allocation.
malloc() stands for memory allocation.
Space dynamically allocated (i.e., at runtime)
with calloc() or malloc() does not get returned
to the system upon function exit. Programmer
must use free() to explicitly return space.
Exercise 14
Write a program that asks the user
how long his or her name is in
characters, dynamically allocates
enough space for a string, and asks
the user to input his or her name,
and stores it in the dynamically
allocated string.
File Handling
Lesson 10
Introduction
Files
Basic Types: text, binary
Reading a file
Writing a file
Flushing streams
Files
A File is a collection of data stored in secondary
memory.
Basic File Types
Text files
Collection of data organized into lines stored as
characters using some coding scheme (ASCII).
Example: c files
Binary files
Collection of data stored as is using the internal
representation scheme (binary).
Example: executable files
Streams
C implements files using streams. A stream is an
abstraction of a file or a device. We need not worry
about the technical details of the underlying file or
device. Our only concern is about the basic
operations like writing and reading.
Kinds of Streams:
Text stream
Sequence of lines. Each line has zero or more
characters and is terminated by '\n'.
Binary stream
Sequence of bytes
How to read/write from a
file?
Basic Steps:
Create a stream variable.
Associate the variable with a file.
Read or write to the file using the
stream variable.
Close the file.
Declaring a Stream
To declare a stream, we write:
FILE *<streamName>;
The FILE object contains all the necessary
information to manipulate a file or a physical
device. You don't need to know these information;
all you need to know are the valid operations or
functions you can use to manipulate files.
Example:
FILE *myFile;
Opening a Stream
To associate the stream with a file,
we do that by opening a stream.
FILE *fopen(const char
*filename, const char *
mode)
Opens the filename in the mode
specified and returns a pointer to
the stream associated with the file.
Opening a Stream
Example:
myFile = fopen("hello.c",
"rt");
if (myFile == NULL)
printf("Error. File
doesn't exist.");
Opening a Stream
For binary files, append “b” at the end
of the mode. For Example:
myFile = fopen("hello.exe",
"rb");
if (myFile == NULL)
printf("Error. File doesn't
exist.");
Writing to a Text file
To write to a file, use the function,
int fprintf(FILE *stream,
const char *
formattedOutput, ...);
This sends formattedOutput to a
stream and returns the number of
characters written, negative if an error
has occurred.
Valid mode parameters for
fopen
r Open an existing TEXT device/file for reading
w Truncate an existing TEXT device/file or, if not present, create it and
then open for writing.
a Open an existing TEXT device/file for appending at the end or create it
if it does not exist.
r+ Open an existing TEXT device/file for reading and writing.
w+ Truncate an existing TEXT device/file or, if not present, create it and
then open for reading and writing.
a+ Open an existing TEXT device/file for appending in both read and write
mode, or create if it does not exist.
Valid mode parameters for
fopen
rb Open an existing BINARY device/file for reading
wb Truncate an existing BINARY device/file or, if not present, create it
and then open for writing.
ab Open an existing BINARY device/file for appending at the end or
create it if it does not exist.
rb+ Open an existing BINARY device/file for reading and writing.
wb+ Truncate an existing BINARY device/file or, if not present, create it
and then open for reading and writing.
ab+ Open an existing BINARY device/file for appending in both read and
write mode, or create if it does not exist.
Writing to a Text file
Example:
char string[] = "stream";
fprintf(myFile, "I am writing to a %s",
string);
Reading from a Text file
To read from a text file, we use the
function,
int fscanf(FILE *stream,
const char *
formattedOutput, ...);
This performs formattedOutput from a
stream and returns the number of input
items converted and assigned, EOF if
end-of-file occurs before conversion.
Reading from a Text file
Example:
char string[], ch;
fscanf(myFile, "%s",
string);
fscanf(myFile, "%c",
&ch);
Reading from a Binary File
To read from a binary file, we use the function,
size_t fread(void *container, size_t
numOfBytes, size_t numOfObj, FILE
*stream);
This reads numOfObj items of size numOfBytes each and
stores the read values into container. It then returns
number of objects (not number of bytes) read which may be
less than the number requested (numOfObj) when the end-
of-file has been reached.
Reading from a Binary File
Example:
int age;
if (fread(&age, sizeof(int), 1, myFile)!
=1)
printf("Cannot read age. Error or
EOF.")
else
printf("Age: %d", age);
Writing to a Binary file
To write to a binary file, we use the
function,
size_t fwrite(void *arg,
size_t numOfBytes, size_t
numOfObj, FILE *stream);
This writes numOfObj items of size
numOfBytes each to the stream and
returns number of objects (not number
of bytes) written; may be less than the
number requested (numOfObj) on error.
Writing to a Binary file
Example:
int age;
if (fwrite(&age,sizeof(int),1,myFile)!= 1)
printf("Error: Cannot write age.");
else
printf("Successful write!");
Checking for end-of-file
status
To check for end-of-file, we use the function,
int feof(FILE *stream)
This
returns non-zero if end-of-file indicator has
been reached.
Example:
while(!feof(myFile)) {
char line[8];
fscanf(myFile, "%[^\n]\n", line);
printf("%s\n", line);
}
Flushing the stream
We use the function fflush in order
to flush a stream; write all unwritten
data and/or discards all unread data.
Returns EOF if an error occurred,
zero otherwise.
Flushing the stream
To disassociate a file from a stream,
we use the function fclose; in
addition, it flushes the stream
Example:
fflush(stdin);
fclose(fp);
Function prototypes for I/O
functions
FILE * fopen(const *name, const char *mode);
int fprintf( FILE *stream, const char *format, … );
int fscanf( FILE *stream, const char *format, … );
int fclose( FILE *stream );
int fflush( FILE *stream );
char *fgets( char *buff, int num, FILE *stream );
int fputs(const *array, FILE *stream);
int fgetc( FILE *stream );
int fputc( int c, FILE *stream );
Lesson Review
A File is a collection of data stored in
secondary memory. Its basic types
are text files and binary files.
A stream is an abstraction of a file or
a device. Kinds of streams are text
streams and binary streams.
Lesson Review
The basic steps to follow to read/write from/to
a file are:
Create a stream variable.
Associate the variable with a file.
Read or write to the file using the stream
variable.
Close the file.
Exercise 15
Write a program that reads the
contents of a text file specified by
the user and outputs it to screen,
line per line. No line in the file is
expected to be longer than 256
characters.
End