Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

CSC103: Introduction to Computer

and Programming

1
Today’s lecture outline

2
Today’s lecture outline
• Introduction to File
• File operations
– Reading from file (character by character)
– Writing in file (character by character)
• File opening mode
• String (line) I/O in Files
– Reading a string
– Writing a string
• Reading and writing numbers in file
• Text vs. binary file
• Reading and writing in binary file
3
File
• Until now we have been saving record in volatile
memory i.e. RAM
– E.g. entering books record, display and search
facility (struct book)
• File can be used to store data permanently i.e. on
hard disk
• Data in files can be retrieve even the computer is
powered off
• C programmer is able to read, write, modify and
delete the content of file

4
Cont.
• A common data file hierarchy is typically
broken down into five categories
– Bit Binary : digit, 0 or 1
– Byte : Eight bits
– Field : Grouping of bytes
– Record : Grouping of fields
– File : Grouping of records

5
Fields, Records
• Fields could be a name, cgpa, department, street
address, phone number, and so on
• Records are logical groupings of fields that comprise
a single row of information
• A student record might be comprised of name, age,
ID, and GPA fields. Each field is unique in description
but together describes a single record.
Field Record
Name ID CGPA Department
Ali Ahmad 105 3.85 Computer science
Fahad Hamid 109 3.75 Computer science

6
Data file
• Data files are comprised of one or more records
• Files can be used to store all types of information,
such as student or employee data

Fatima Tariq 102 3.45 Physics


Ali Ahmad 105 3.85 Computer science
Fahad Hamid 109 3.75 Computer science

• C programmers use pointers to manage file for


reading and writing data

7
File Operations
• Creation of a new file
• Opening an existing file
• Reading from a file
• Writing to a file
• Moving to a specific location in a file (seeking)
• Closing a file

8
Example program

Go to program

9
Opening a File
• Before reading and writing operation on file, file
must be opened
• fopen() function can be used to open a file
• Example program opens ”prog1.c” file in read mode
• Read mode means content of file cannot be modified
or added, they can just be read

string string

10
Tasks of fopen( ) function
1. Firstly it searches on the disk the file to be
opened
2. Then it loads the file from the disk into a
place in memory called buffer
3. It sets up a character pointer that points to
the first character of the buffer
It is much faster to read / write content in
memory as compare to hard disk

11
Cont.

12
structure FILE
• For successful reading from a file information like
mode of opening, size of file, place in the file
from where the next read operation would be
performed, etc. has to be maintained
• fopen( ) store such information in a FILE structure
and returns it address
• We store that address in a pointer of type FILE

13
Reading from a File
• Once file is opened using fopen ( ), its content are
brought into buffer
• A pointer is set that points to the first character in
this buffer
• This pointer is one of the elements of the
structure to which fp is pointing
• To read the file’s contents from memory we use a
function called fgetc( )

14
Cont.
ch = fgetc ( fp ) ;
• fgetc( ) reads the character from the current pointer
position
• advances the pointer position so that it now points
to the next character, and
• returns the character that is read
*fp 855 405
406
855

h e l l o w o r l d
405 406 407
ch = fgetc ( fp ) ; ch h
15
Cont.
• Once the file is opened, we can refer file not by its
name but through FILE pointer
• The function fgetc( ) within an indefinite while loop
• Loop will be executed until if finds End Of File (EOF)

• EOF is a special character whose ASCII value is 26


• EOF is inserted after the last character in the file
h e l l o w o r l d EOF
405
• EOF is macro has been defined in the file stdio.h.
16
Trouble in Opening a File
• There is a possibility that when we try to open a file
using the function fopen( ), the file may not be
opened
• For example, the file may not exist on the disk
• Other reasons may be
• disk space may be insufficient to open a new file,
or the disk may be write protected or the disk is
damaged and so on
• If the file opening fails the fopen( ) function returns a
value NULL

17
Example code

This check must be performed for


every program that involve File I/O

18
Closing the File
• After reading/writing from the file, file should be
closed
• Once file is closed, it is not possible to perform
read/write operation
• Three operations would be performed by fclose( )
– The characters in the buffer would be written to
the file on the disk
– At the end of file a character with ASCII value 26
would get written (EOF character)
– The buffer would be eliminated from memory

19
Example program
• Write a program that will read a file and count
how many characters, spaces, tabs and
newlines are present in it

write a program

20
Writing character in file
• fputc( ) is used to writes character in a file
fputc ( ch, fp ) ;

Character variable File pointer

fputc write the character constant store in


character variable in the buffer that is pointer
by a pointer fp

21
A File-copy Program
• Write a program that create a copy of a file.
The user input two file names
– the name of file to be copied
– Copy file name

write a program

22
File Opening Modes
• "r" :
reading from file, if file does not exist it
returns null
• "w" :
writing to the file, if file does not exits a new
file is created
• "a" :
adding new contents at the end of file, if file
does not exits a new file is created

23
File opening mode
• "r+" :
Reading, writing, modifying content of file, if file
does not exist it returns null
• "w+" :
Reading, writing, modifying content of file, if file
does not exits a new file is created
• "a+" :
Reading, adding new contents at the end of file,
cannot modify existing contents. if file does not
exits a new file is created

24
Writing string in a file
fputs ( s, fp ) ;
• fputs( ) function writes the contents of the array
pointer by pointer s to the file pointed by pointer
fp

Go to program

Enter a few lines of text


Hello world Hello world
C programming C programming

25
Reading string from a file
fgets ( s, 79, fp ) ;
• This function read 79 bytes (character) from file
pointed by pointer fp and write in the memory
address s.
• s is base address of a character array
• This function returns NULL if no record is available to
read

Go to program

26
New line character
• If we write the following on file using fputs
Hello world
programming
• Actual number of character in file are 24
• But the size of file will be 26
• Reason : fputs( ) converts the \n to \r\n
combination

27
Cont.
• If we read the same line back using fgets( ) the
reverse conversion happens.
• Thus when we write the first line of the poem
and a “\n” using two calls to fputs( ), what
gets written to the file is
Baa baa black sheep have you any wool \r\n

Go to program

28
Writing integer and float in file
• Until now we have seen following functions
– fgetc(fp); fputc(ch, fp);
– fgets(s, 79, fp); fputs(s, fp)
• C provide functions to write integer and float
values in file
– fprintf - use to print (write) on file
– fscanf - use to scan (read) a file

29
fprintf Syntax

• printf(“%s %f %d”, b1.name, b1.price, b1.pages);


It prints let us c 350.75 550 on standard output (monitor)

• fprintf(fp, “%s %f %d”, b1.name, b1.price, b1.pages);


it prints lets us c 350.75 550 on file pointed by pointer fp

30
fscanf syntax

• scanf(“%s %f %d”, b1.name, &b1.price, &b1.pages);


It scan/read values (name, price, pages) from
standard input (keyboard)
• fscanf(fp, “%s %f %d”, b1.name, &b1.price, &b1.pages
);
It scan/read values (name price, pages) from a file
pointed by pointer fp
31
Example program – fprintf
• Input record for employ
– Name
– Age
– Basic salary
• Input record as much as user required
• Write record in file employee.dat

Go to program

32
Example program – fscanf
• Write a program to display the content of file
that have been created in the previous
example program
– Name
– Age
– Basic salary

Go to program

33
Text Files and Binary Files
• A text file contains only textual information like
alphabets, digits and special symbols.
• Actually the ACSII values of these characters are
stored in text file
• Example of binary file is .exe file or music data stored
in a wave file etc.
• To open binary file we have
– “rb” same as “r”
– “wb” same as “w”

34
Differences between text and binary files

• There are three main areas where text and


binary mode files are different. These are:
– Handling of newlines
– Representation of end of file
– Storage of numbers

35
Handling of newlines

• In text mode
– When writing to file :new line (\n) is
replaced by carriage return plus new line
combination (\r\n)
– When reading from file: \r\n is replaced by
\n
• In binary mode these conversion does not
take place

36
End of File
• In text mode, a special character, whose ASCII value
is 26, is inserted after the last character in the file to
mark the end of file
• In binary mode there is no such special character
present to mark the end of file
• The binary mode files keep track of the end of file
from the number of characters present in the
directory entry of the file
• File written in text mode must be read in text mode
• File written in binary mode must be read in binary
mode

37
Storage of Numbers
• fprintf is the function that is used to write number in
file
• How numeric data is stored using fprintf
– Character takes one byte
– Does float or integer takes 4 bytes : No
– Numbers are stored as string of character e.g 34512
takes 5 bytes and 34566.4563 takes 10 bytes
– Thus, numbers with more digits would require more
disk space.
• If large amount of numerical data is to be stored in a
file, using text mode may turn out to be inefficient.
38
Cont.
• Solution is to used binary mode
• Binary mode stores the numbers in binary
format
• It means each number would occupy same
number of bytes on disk as it occupies in
memory

39
Reading content from binary file
• fread() is used to read the content from binary
file
fread ( &e, sizeof ( e ), 1, fp )
Memory Read from
address to No of bytes to read Number of Block to buffer
write content from fp, specified in read, each block size pointer by
read from fp 4th argument is specified in 2nd pointer fp
parameter

Read from fp, 1 block containing sizeof(e) bytes


and write it at address &e
40
Writing content in binary file
• fwrite() is used to write the content in binary
file
fwrite( &e, sizeof ( e ), 1, fp )
Memory
address to Write the
read the No of bytes to read Number of Block of content (read
content from memory size as specified in form address
address specified in 2nd parameter to specified in 1st
1st argument read parameter) to
buffer pointer
by pointer fp
Read 1 block containing sizeof(e) number of
bytes from address &e and write it to fp
41
42

You might also like