0% found this document useful (0 votes)
50 views30 pages

PL1 Lecture 09

The document discusses sequential and random access of files in C programming. It covers opening files in different modes for reading and writing text and binary files sequentially. Random access allows non-sequential access to files using file pointers. Functions like fscanf and fprintf are used for sequential text I/O while feof tests for end of file. Closing files frees resources with fclose.

Uploaded by

mustfa khedr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views30 pages

PL1 Lecture 09

The document discusses sequential and random access of files in C programming. It covers opening files in different modes for reading and writing text and binary files sequentially. Random access allows non-sequential access to files using file pointers. Functions like fscanf and fprintf are used for sequential text I/O while feof tests for end of file. Closing files frees resources with fclose.

Uploaded by

mustfa khedr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

CS112 – Level 1

Programming Languages 1

Lecture 9
File Processing [ Part 2 ], Sequential / Random
Access, Bitwise Operations, .. & .. Command-Line
Arguments

Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of
New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
2

• C File Processing [ Part 2 ]

O • Text Files and Binary Files


u
t • Files: Sequential Access

Outline l
i • Files: Random Access
n
• Bitwise
e Operations
• Using Command-Line Arguments

2
The ability to read data from and write data to files is the primary means of
storing persistent (permanent) data, or data which does not disappear when
your program finishes running.
File I/O Recap ..
Why Files?

 Storage of data in variables and arrays is temporary—such data is lost when a


program terminates.
 Files are used for permanent retention of data.
 Computers store files on secondary storage devices, especially disk storage
devices.
 The C programming language provides many standard library functions for
file input and output. These functions are found in the C standard library
header stdio.h.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs
Recap ..
Files and Streams
 C views each file simply as a sequential stream of bytes.
 In computer science, a stream is a sequence of data elements made available
over time.
 Normal functions cannot operate on streams as a whole, as they have
potentially unlimited data
 In C, the stream is a common, logical interface to the various devices of the
computer. All input and output is performed with streams, which are
sequences of bytes.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs
Recap ..
Files and Streams
 A stream is linked to a file using an open operation, and is disassociated from
a file using a close operation.
 Each file stream ends with an end-of-file marker (EOF).
 Opening a file stream returns a pointer to a FILE structure that contains
information used to process the file.
 Three streams are automatically opened when program execution begins—
the standard input, the standard output, and the standard error.
 The standard input stream enables a program to read data from the
keyboard, and the standard output stream enables a program to print data
on the screen.
o C views each file as a sequence of bytes.
o A file ends with the end-of-file marker.
o A stream is created when a file is opened.
o Provides a communication channel between files and programs
Recap ..
Files and Streams
Step 1: Create a reference to the file (a file pointer)
FILE* fptr;
Step 2: Open the file (using the fopen function) Recap ..
fptr = fopen(“client.txt”, “r”);
Step 3a: Read from the file
 fgetc -- fgets -- fread -- fseek -- .. etc.
Step 3b: Write to the file
 fputc -- fputs -- fprintf -- fwrite -- .. etc.
Step 4: Close the file
fclose(file);
Remember!
 Always open a file before reading from or writing to it
 Always check the return value to make sure you don't get
back a NULL.
 Always close a file if you open it
Text Files
.. versus ..
Binary Files
8
Text Files versus Binary Files

 Each file is just a series of bytes.


 In general, every file is a binary file, but if the data in it
contains only text, then we could consider it a text file.
 E.g., A C program written in the editor is a text file, but its
compiled version is binary.
 A text file is a stream of characters that a computer can
process sequentially and in forward direction. They can
only read or write data one character at a time. Some
special-characters conversion may occur in
input/output operations in text mode.
 A binary file is a collection of bytes. No special
processing occurs during the transferring of data
between the disk and the memory.
Text Files versus Binary Files ..
MODES FOR TEXT FILES
 r .. Open and existing file for reading. The stream is positioned at the
beginning of the file.
 r+ .. Open an existing file for reading and writing. The stream is positioned
at the beginning of the file.
 w .. Truncate file (if it exists) to zero length (discard its contents) or create a
text file for writing. The stream is positioned at the beginning of the file.
 w+ .. Open for reading and writing. The file is created if it does not exist,
otherwise it is truncated (contents are discarded). The stream is positioned
at the beginning of the file.
 a .. Open for appending (writing at the end of the file). The file is created if
it does not exist. The stream is positioned at the end of the file.
 a+ .. Open for reading and appending (writing at end of file). The file is
created if it does not exist. The initial file position for reading is at the
beginning of the file, but output is always appended to the end of the file.
Text Files versus Binary Files ..
MODES FOR BINARY FILES
 rb .. Open and existing file for reading. The stream is positioned at the
beginning of the file.
 rb+ .. Open an existing file for reading and writing. The stream is
positioned at the beginning of the file.
 wb .. Truncate file (if it exists) to zero length (discard its contents) or create
a text file for writing. The stream is positioned at the beginning of the file.
 wb+ .. Open for reading and writing. The file is created if it does not exist,
otherwise it is truncated (contents are discarded). The stream is positioned
at the beginning of the file.
 ab .. Open for appending (writing at the end of the file). The file is created
if it does not exist. The stream is positioned at the end of the file.
 ab+ .. Open for reading and appending (writing at end of file). The file is
created if it does not exist. The initial file position for reading is at the
beginning of the file, but output is always appended to the end of the file.
Sequential Access
.. versus ..
Random Access

12
Sequential Access Files .. TEXT FILES
• Use fprintf and fscanf, both of which are similar to their friends printf and
scanf, except that you must pass the FILE pointer as the first argument.
E.g., fscanf( fPtr, "%d %s", &account, name);
• fscanf and fprintf can deal with the standard input/output by using stdin
or stdout as the file pointer, as in:
fprintf( stdout, "%s \n", “test”);
• When you have finished working with a file, you should close it using the
function:
int fclose(FILE *a_file);
fclose returns a zero if the file is closed successfully. Closing a file can free
resources for which other users or programs may be waiting for.
Example
Sequential When
If theaprogram
you use reaches
string literal, the end of the
use double
Access Files file, Function
backslashes feof than
rather returns
Reading
Open
true backslash!
a single
file
from
for
after the It's
just the way
program quoted
attempts strings
to read are
the
File Pointer handled in C
nonexistent
int account; and reading
file
dataC++.
following the last line.
char name[ 30 ];
double balance;
FILE *fPtr;
if ( ( fPtr = fopen( "c:\\clients.dat", "r" ) ) == NULL )
printf( "File could not be opened\n" );
else {
Means the file can’t
printf( "%-10s%-13s%s\n", "Account", be opened
"Name", "Balance" );
fscanf( fPtr, "%d%s%f", &account, name, &balance );
while (!feof( fPtr ) ) {
printf( "%-10d%-13s%7.2f\n", account, name, balance );
fscanf( fPtr, "%d%s%f", &account, name, &balance );
} /* end while */
fclose( fPtr );
}
Sequential Access Files .. TEXT FILES
Resetting the File Position Pointer
• A program normally starts reading from the beginning of the file,
and reads all data consecutively (sequentially, one after the other).
• The File position pointer is an integer that indicates the index of
the next byte in the file to be read or written. This is sometimes
referred to as the file offset.
• The file position pointer is a member of the FILE structure
associated with each file.
• A statement rewind( fPtr ) causes a program’s file position pointer
to be repositioned to the beginning of the file (i.e., byte 0).
Random Access Files .. BINARY
FILES
• Random access means we can move to any part of a file and
read or write data from it without having to read through the
entire file.
• Individual records of a random access file are normally fixed in
length and may be accessed directly (and thus quickly).
• The exact location of a record relative to the beginning of the
file can be calculated.
• Data can be inserted in a random-access file without
destroying other data in the file. Data stored previously can
also be updated or deleted without rewriting the entire file.
Random Access Files .. BINARY
FILES
• Function fread reads a specified number of bytes from the
location in the file specified by the file position pointer
• Function fwrite writes a specified number of bytes to a file.
The data is written beginning at the location in the file
indicated by the file position pointer.
• Example:
fwrite( &data, sizeof( int ), 1, fPtr );
In sequential access it was:
fprintf( fPtr, "%d", number );
Random Access Files .. BINARY
FILES
 Function fseek sets the file position pointer to a specific position
in the file, then fwrite writes the data.
int fseek( FILE *stream, long int offset, int whence );
 offset: is the number of bytes to seek from location whence in
the file pointed to by stream.

 The argument whence can have one of three values:


 SEEK_SET: seek starts at the beginning of the file.
 SEEK_CUR: seek starts at the current location.
 SEEK_END: seek starts at the end of the file.
Random Access Files .. EXAMPLE
struct Data {
int acctNum; char lastName[ 15 ];
char firstName[ 10 ]; double balance; }
int main() {
struct Data D = { 0, "", "", 0.0 };
FILE * fptr;
if ( ( fptr = fopen( "credit.dat", "wb" ) ) == NULL ) {
printf( "File could not be opened.\n" ); }
else {
fwrite( &D, sizeof( struct Data ) , 1 , fptr );
fclose( fptr );
}
Size of the record which will be written
return 0
};
Number of records which will be
written .. could be an array
Random Access Files .. EXAMPLE

struct Data D;
FILE * fPtr;
if ( ( fPtr = fopen( "credit.dat", "rb" ) ) == NULL ) {
printf( "File could not be opened.\n" ); }
else { The byte positions in the file
int Num; Starts with 0
scanf( "%d", Num);
fseek( fPtr, ( Num - 1 ) *sizeof( struct Data ), SEEK_SET );
fread( &D, sizeof( struct Data ), 1, fPtr );
printf( "%d %s %s %f\n", D.acctNum, client.lastName,
D.firstName, D.balance );
fclose( fptr );
}
Files I/O [ Input / Output ]
char c = fgetc( fptr ); //returns/reads one character
fputc( c, cfptr ); //puts/writes one character to a file
E.g.:
while ( (c = fgetc( fptr ) ) != EOF ) End of file
printf("char: '%c'\n", c );

The file: The output:


UW char: 'U'
CE char: 'W'
char: '
'
char: 'C'
char: 'E'
char: '
'
Bitwise
Operators

22
Bitwise Operators

 Sometimes it becomes mandatory to consider data at the bit level.


 We have to operate on an individual data bit. We might need to
turn on/off a particular data bit during source code drafting. In such
situations, we must use bitwise operators to manipulate the bits
easily.
 The C Programming Language provides us with different bitwise
operators to manipulate the bits.
 Bitwise operators operates on integer and character variables, but
not on float or double variables.
Bitwise Operators
C Programming Language supports
6 bitwise operators:
Bitwise Operators .. An Example
Displaying an Integer in bits:
void bit_dis( int value ) {
int i;
mask =
int size = 8 * sizeof( int ); 10000000000000000000000000000000
unsigned int mask = 1 << size - 1;
printf( "%-10d =", value );
for ( i = 0; i < size; i++ ) {
( value & mask ) ? putchar('1'): putchar('0');
mask = mask >> 1; // mask >> = 1
For example, if value = 5
}
5 = 00000000000000000000000000000101
putchar('\n');
}
Bitwise Operators .. An Example
Displaying an Integer in bits:
int main() { For example, if x = 3:
0 0 1 1 [3]
int i, x = 60; 0 1 1 0 [6] shift left by 1
1 1 0 0 [12] shift left by 2
for( i = 1; i < 4; i++ )
{
Multiply byprintf("Multiply
2^1 = 120 by 2^%d = %10d\n", i, x << i );
Divide by 2^1 = 30
Multiply by//2^2
Shifting
= 240 left means multiplying by 2i
Divide by 2^2 = 15
printf("Divide by 2^%d = %10d\n", i, x >> i );
Multiply by 2^3 = 480
// Shifting
Divide by 2^3 =7 right means dividing by 2i
}
return 0;
}
Command-Line
Arguments

27
Command-Line Arguments
It’s possible to pass arguments to the main from a command line by including
parameters: int argc and char *argv[] in the parameter list of the main.
argc: argument count (an integer variable)
 The number of arguments that are passed to main in the argument vector
argv.
 The value of argc is always one greater than the number of command-line
arguments that the user enters.
argv: argument vector (array of strings)
 An array of string pointers passed to the C program's main function.
 argv[ 0 ] is always the name of the command (program name).
 argv[ argc ] is a null pointer.
Command-Line Arguments .. An Example
Calculate x to the power of y
int main( int argc, char *argv[ ] ) {
if ( argc != 3 ) { printf( "ERROR!!\n" ); // file name and 2 parameters
} else {
int x, y, power = 1, i;
x = argv[ 1 ][ 0 ] - '0'; // to convert the string to an integer
y = argv[ 2 ][ 0 ] - '0';
for( i = 1; i <= y; i++ )
power*= x;
printf( "\t%d", power );
}
Thanks! .. Questions?

30

You might also like