SlideShare a Scribd company logo
1 of 48
COM1407
Computer Programming
Lecture 14
File Processing
K.A.S.H. Kulathilake
B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK)
Rajarata University of Sri Lanka
Department of Physical Sciences
1
Objectives
• At the end of this lecture students should be able
to;
▫ Define the C standard functions for managing file
input output.
▫ Apply taught concepts for writing programs.
2
Introduction
• The file is the basic unit of storage for many
operating systems.
• Although C does not have any built-in method
for performing file I/O, the C standard library
contains a very rich set of I/O functions
providing and efficient, powerful and flexible
approach.
• Those functions can read or write any type of
data to files.
3
What is a File?
• In C, a file can refer to a disk file and every disk file
has a name.
• Filenames are stored as strings, just like other text
data.
• In DOS and Windows 3.X, a complete filename
consists of a name that has from one to eight
characters, optionally followed by a period and an
extension that has from one to three characters.
• In contrast, the Windows 95 and Windows NT OS,
as well as most UNIX systems, permit filenames
upto 256 characters long.
4
What is a File? (Cont…)
• A file name in C program also can contain path
information.
• The path specifies the drive and or directory where
the file is located.
▫ C:DATAlist.txt  this is a good programming
practice to specify path information.  is used to
separate the directory names in the path.
• If you specify a filename without a path, it will be
assumed that the file is located at whatever location
the OS currently designates as the default.
char* filename = “C:DATAlist.txt”;
5
What is a Stream?
• The data flow you transfer from your program to a file,
or vice versa, is called a stream which is a series of bytes.
• Hence, a stream is a sequence of bytes travelling from a
source to a destination over a communication medium.
• Streams can either be input or output.
• The input stream is used for reading while the output
stream is used for writing.
• Unlike a file, which targets a specific I/O device, a
stream is device independent.
• You can perform I/O operations to any type of file by
simply associating a stream to the file.
6
What is a Stream? (Cont…)
• There are two formats of streams.
• Text streams
▫ Consists of sequence of characters.
▫ Depending on the system, each line of characters
in a text stream may be terminated by a newline
character.
▫ Text streams are used for textual data, which has a
consistent appearance from one environment to
another, or from one machine to another.
7
What is a Stream? (Cont…)
• Binary stream
▫ It consists of series of bytes, e.g., the contents of
an executable program file.
▫ Binary streams are primarily used for nentextual
data, where the exact contents of the data are
maintained without regard to appearance.
8
Buffered I/O
• In C, a memory area that is temporarily used to store
data before it is sent to its destination is called a buffer.
• With the help of buffers, the operating system can
improve efficiency by reducing the number of accesses to
I/O devices (that is files).
• Access to a disk or other I/O device is generally much
slower than direct access to memory.
• Several I/O operations can be performed on a buffer that
represents the I/O file, instead of the file itself.
• e.g. if several write operations are sent to a buffer, they
are kept in memory until it is time to save, or commit,
the new data to the actual device.
9
Pointers of FILE
• The FILE structure is the file control structure
defined in the header file stdio.h.
• A pointer of type FILE is called a file pointer,
which references a disk file.
• A file pointer is used by a stream to conduct the
operation of the I/O function.
• e.g. following defines a file pointer called fptr;
FILE *fptr;
10
Opening a File
• fopen() opens a file and associates a stream with the
opened file.
#include <stdio.h>
FILE *fopen( const char* filename,
const char *mode);
• Here, filename is a char pointer that references a string
containing a filename.
• Mode points to another string that specifies the way to
open the file.
• The fopen() function returns a pointer of type FILE in a
success scenario otherwise null pointer is returned.
11
Opening a File (Cont…)
12
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing. If it does not exist, then a new file is created. Here
your program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode. If it does not exist, then a new
file is created. Here your program will start appending content in the existing
file content.
r+ Opens a text file for both reading and writing.
w+ Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.
a+ Opens a text file for both reading and writing. It creates the file if it does not
exist. The reading will start from the beginning but writing can only be
appended.
Opening a File (Cont…)
13
Mode Description
rb Opens an existing binary file for reading
wb Creates a binary file for writing
ab Opens an existing binary file for appending
r+b or
rb+
Opens an existing binary file for reading or writing
w+b or
wb+
Creates a binary file for reading or writing
a+b
ab+
Opens or creates a binary file for appending
Opening a File (Cont…)
#include <stdio.h>
int main ()
{
FILE *fptr;
fptr = fopen("test.txt","r");
if (fptr == NULL )
{
printf("Cannot open file.n");
exit (1);
}
else
{
printf("File opens successfully.n");
}
return 0;
}
14
Closing a File
• After a disk file is read, written or appended with some new data,
you have to disassociate the file from a specified stream by calling
the fclose() function.
#include <stdio.h>
int fclose ( FILE *stream );
• Here stream is a file pointer that is associated with a stream to the
opened file.
• If fclose() closes a file successfully, it returns 0, otherwise it returns
EOF.
• Normally, fclose() fails only when the disk is removed before the
function is called or there is no more space left on the disk.
• The fclose() flushes data left in the buffer to ensure that no data will
be lost before it disassociates a specified stream with the opened file.
15
Closing a File (Cont…)
#include <stdio.h>
int main ()
{
FILE *fptr;
fptr = fopen("test.txt","r");
if (fptr == NULL )
{
printf("Cannot open file.n");
exit (1);
}
16
Closing a File (Cont…)
else
{
int status = 0;
printf("File opens successfully.n");
status = fclose(fptr);
if (status == 0 )
printf("Status: %i - File closed
successfully.n", status);
else
printf("Error in file closing.n");
}
return 0;
}
17
I/O Operations
• In C, you can perform I/O operations in the
following ways;
▫ Read or write one character at a time.
▫ Read or write one line of text at a time.
▫ Read or write one block of characters at a time.
18
Read One Character at a Time
• fgetc() fucntion is used to read one character at a time.
#include <stdio.h>
int fgetc( FILE *stream);
• Here stream is the file pointer associated with a stream.
• The fgetc() fetches the next character from the stream.
• The function then returns value of an int that is
converted from the character.
• EOF is returned if fgetc() encounters the end of file or if
there is an error.
19
Read One Character at a Time (Cont…)
#include <stdio.h>
int main ()
{
FILE *fptr;
char fileName [] = "test.txt";
if ( (fptr = fopen (fileName, "r")) == NULL){
printf("Cannot open file.n");
exit (1);
}
else{
int c;
while ( (c = fgetc(fptr))!= EOF){
putchar (c);
}
fclose(fptr);
}
return 0;
}
20
Write One Character at a Time
• fputc() fucntion is used to write one character at a time.
#include <stdio.h>
int fputc (int c, FILE *stream);
• Here c is an int value that represents a character.
• In fact, the int value is converted to an unsigned char
before being output.
• Stream is the file pointer associated with a stream.
• The fputc() returns the character written if the function
is successful; otherwise, it returns EOF.
• After a character is written, the fputc() advances the
associated file pointer.
21
Write One Character at a Time (Cont…)
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("writec.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);
return(0);
}
22
Write One Character at a Time (Cont…)
#include <stdio.h>
#include <string.h>
int main ()
{
FILE *fptr;
char fileName [] = "writec.txt";
char text[100] = "This content to be written
in to a file";
int lstr = strlen( text );
if ( (fptr = fopen (fileName, "w+")) == NULL)
{
printf("Cannot open file.n");
exit (1);
}
23
Write One Character at a Time (Cont…)
else
{
int i;
for(i = 0 ; i <= lstr ; i++)
fputc (text[i],fptr);
printf("End");
fclose(fptr);
}
return 0;
}
24
Activity
#include <stdio.h>
void charReadWrite( FILE*, FILE*);
int main ()
{
FILE *fptr1, *fptr2;
char fileName1 [] = "writec.txt";
char fileName2 [] = "test.txt";
if ( (fptr1 = fopen (fileName1, "w+"))
== NULL){
printf("Cannot open %s file.n", fileName1);
exit (1);
}
else{
25
Activity
if ( (fptr2 = fopen (fileName2, "r"))
== NULL){
printf("Cannot open %s file.n",
fileName2);
exit (1);
}
else{
charReadWrite (fptr2, fptr1);
fclose (fptr1);
fclose (fptr2);
}
}
return 0;
}
26
Activity
void charReadWrite( FILE *fin, FILE *fout)
{
int c;
while ((c = fgetc(fin)) != EOF)
{
fputc(c, fout);
putchar(c);
}
}
27
Read One Line of Text at a Time
• fgets() function is used to read one line at a time.
#include <stdio.h>
char *fgets (char *s, int n, FILE *stream);
• Here s refers a character array that us used to store characters
read from the opened file pointed to by the file pointer
stream.
• n specifies the maximum number of array elements.
• If it is successful, the fgets() function returns a char pointer s.
• If EOF is encountered, the fgets() function returns a null
pointer and leaves the array untouched.
• If an error occurs, the function returns a null pointer, and the
contents of the array are unknown.
28
Read One Line of Text at a Time
(Cont…)
#include <stdio.h>
int main ()
{
FILE *fptr;
char fileName [] = "test.txt";
if ( (fptr = fopen (fileName, "r")) == NULL){
printf("Cannot open file.n");
exit (1);
}
else{
char buff [80];
while ( fgets(buff, 80, fptr)!= NULL){
printf("%s", buff);
}
fclose(fptr);
}
return 0;
}
29
Read One Line of Text at a Time
(Cont…)
• The fgets() can read up to n-1 characters, and
can append a null character after the last
character fetched, until a newline or and EOF is
encountered.
• Note that the new line is encountered during the
read operation, the fgets() function includes the
newline in the array.
• This is different from what the gets() does.
• The gets() just replaces the newline character
with a null character.
30
Write One Line of Text at a Time
• fputs() function is used to write one line at a time.
#include <stdio.h>
char *fputs (const char *s, FILE *stream);
• Here s points to the array that contains the characters to
be written to a file associated with the file pointer
stream.
• The const modifier indicates that the content of the array
pointed to by s cannot be changed by the fputs().
• If it is fails, the fputs() function returns a nonzero value;
otherwise, it returns zero.
31
Write One Line of Text at a Time
(Cont…)
• Note that the character array must include a null
character at the end of the string as the
terminator to the fputs().
• Also, unlike the puts(), the fputs() does not
insert a newline character to the string written to
the file.
32
Write One Line of Text at a Time
(Cont…)
#include <stdio.h>
#include <string.h>
int main ()
{
FILE *fptr;
char fileName [] = "writec.txt";
char text[100] = "This content to be written in to a filen";
int lstr = strlen( text );
if ( (fptr = fopen (fileName, "w+")) == NULL){
printf("Cannot open file.n");
exit (1);
}
else{
int i=0;
for(;i<10;i++)
fputs(text, fptr);
fclose(fptr);
}
return 0;
}
33
Activity
#include <stdio.h>
void lineReadWrite( FILE*, FILE*);
const int MAX_LEN = 81;
int main ()
{
FILE *fptr1, *fptr2;
char fileName1 [] = "writec.txt";
char fileName2 [] = "test.txt";
if ( (fptr1 = fopen (fileName1, "w+")) == NULL)
{
printf("Cannot open %s file.n", fileName1);
}
34
Activity
else
{
if ( (fptr2 = fopen (fileName2, "r")) == NULL)
{
printf("Cannot open %s file.n", fileName2);
}
else
{
lineReadWrite (fptr2, fptr1);
fclose (fptr1);
fclose (fptr2);
}
}
return 0;
}
35
Activity
void lineReadWrite( FILE *fin, FILE *fout)
{
char buff[100];
while ( fgets(buff, MAX_LEN, fin) != NULL)
{
fputs(buff, fout);
printf( "%s", buff);
}
}
36
Read One Block of Text at a Time
• fread() is used to reading one block of text at a time.
#include <stdio.h>
size_t fread ( void *ptr, size_t size, size_t n,
FILE *stream);
• Here ptr is a pointer to an array in which the data is stored.
• Size indicates the size of each array element.
• N specifies the number of elements to read.
• Stream is a file pointer that is associated with the opened file
for reading.
• size_t is a integral type of defined in the header file stdio.h.
• The fread() returns the number of elements actually read.
37
Read One Block of Text at a Time
(Cont…)
• The number of elements read by the fread()
function should be equal to the value specified
by the third argument to the function, unless an
error occurs or and EOF is encountered.
• The fread() returns the number of elements that
are actually read during the attempt, if an error
occurs or an EOF is encountered.
38
Write One Block of Text at a Time
• fwrite() is used to write one block of text at a time.
#include <stdio.h>
size_t fwrite( const void *ptr, size_t size,
size_t n,FILE *stream);
• Here ptr references the array that contains the data to be written to
an opened file pointed to by the file pointer stream.
• size indicates the size of each element in the array.
• n specifies the number of elements to be written.
• The fwrite() function returns the number of elements actually
written.
• If no error has occurred, the value written by fwrite() should equal
the third argument in the function.
• The return value may be less than the specified value in an error
occurs.
39
Write One Block of Text at a Time
(Cont…)
• Note that it is programmers’ responsibility to ensure
that the array is large enough to hold data for either
the fread() or the fwrite().
• In C, a function called feof() can be used to
determine when the end of a file is encountered.
#include <stdio.h>
int feof(FILE *stream);
• The feof() returns 0 if the end of the file has not
been reached; otherwise, it returns the non zero
integer.
40
Write One Block of Text at a Time
(Cont…)
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "This is about fread() and fwrite()";
char buffer[100];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
/* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp);
41
Write One Block of Text at a Time
(Cont…)
/* Seek to the beginning of the file */
fseek(fp, 0, SEEK_SET);
/* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%sn", buffer);
fclose(fp);
return(0);
}
42
Activity
#include <stdio.h>
void blockReadWrite( FILE*, FILE*);
const int MAX_LEN = 81;
int main ()
{
FILE *fptr1, *fptr2;
char fileName1 [] = "writec.txt";
char fileName2 [] = "test.txt";
if ( (fptr1 = fopen (fileName1, "w+")) == NULL)
{
printf("Cannot open %s file.n", fileName1);
}
43
Activity
else
{
if ( (fptr2 = fopen (fileName2, "r")) == NULL)
{
printf("Cannot open %s file.n", fileName2);
}
else
{
blockReadWrite (fptr2, fptr1);
fclose (fptr1);
fclose (fptr2);
}
}
return 0;
}
44
Activity
void blockReadWrite( FILE *fin, FILE *fout)
{
int num;
char buff[100];
while (!feof(fin))
{
num = fread(buff, sizeof(char), MAX_LEN, fin);
buff[num * sizeof(char)] = '0';
printf( "%s", buff);
fwrite(buff, sizeof(char), num,fout);
}
}
45
Objective Re-cap
• Now you should be able to:
▫ Define the C standard functions for managing file
input output.
▫ Apply taught concepts for writing programs.
46
References
• Chapter 16 - Programming in C, 3rd Edition,
Stephen G. Kochan
47
End of COM1407
Next: Data Structures & Algorithms, Compute Graphics &
Image Processing
48

More Related Content

What's hot

What's hot (18)

Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
C files
C filesC files
C files
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Handling in C
File Handling in C File Handling in C
File Handling in C
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 

Similar to COM1407: File Processing

Similar to COM1407: File Processing (20)

File management
File managementFile management
File management
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
Handout#01
Handout#01Handout#01
Handout#01
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File mangement
File mangementFile mangement
File mangement
 
File management
File managementFile management
File management
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File management in C++
File management in C++File management in C++
File management in C++
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
Files in c++
Files in c++Files in c++
Files in c++
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Presentation of file handling in C language
Presentation of file handling in C languagePresentation of file handling in C language
Presentation of file handling in C language
 

More from Hemantha Kulathilake

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar Hemantha Kulathilake
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishHemantha Kulathilake
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelHemantha Kulathilake
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingHemantha Kulathilake
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation Hemantha Kulathilake
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 

More from Hemantha Kulathilake (20)

NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar NLP_KASHK:Parsing with Context-Free Grammar
NLP_KASHK:Parsing with Context-Free Grammar
 
NLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for EnglishNLP_KASHK:Context-Free Grammar for English
NLP_KASHK:Context-Free Grammar for English
 
NLP_KASHK:POS Tagging
NLP_KASHK:POS TaggingNLP_KASHK:POS Tagging
NLP_KASHK:POS Tagging
 
NLP_KASHK:Markov Models
NLP_KASHK:Markov ModelsNLP_KASHK:Markov Models
NLP_KASHK:Markov Models
 
NLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram ModelsNLP_KASHK:Smoothing N-gram Models
NLP_KASHK:Smoothing N-gram Models
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
NLP_KASHK:N-Grams
NLP_KASHK:N-GramsNLP_KASHK:N-Grams
NLP_KASHK:N-Grams
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
NLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological ParsingNLP_KASHK:Finite-State Morphological Parsing
NLP_KASHK:Finite-State Morphological Parsing
 
NLP_KASHK:Morphology
NLP_KASHK:MorphologyNLP_KASHK:Morphology
NLP_KASHK:Morphology
 
NLP_KASHK:Text Normalization
NLP_KASHK:Text NormalizationNLP_KASHK:Text Normalization
NLP_KASHK:Text Normalization
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions NLP_KASHK:Regular Expressions
NLP_KASHK:Regular Expressions
 
NLP_KASHK: Introduction
NLP_KASHK: Introduction NLP_KASHK: Introduction
NLP_KASHK: Introduction
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation COM1407: Structures, Unions & Dynamic Memory Allocation
COM1407: Structures, Unions & Dynamic Memory Allocation
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

COM1407: File Processing

  • 1. COM1407 Computer Programming Lecture 14 File Processing K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  • 2. Objectives • At the end of this lecture students should be able to; ▫ Define the C standard functions for managing file input output. ▫ Apply taught concepts for writing programs. 2
  • 3. Introduction • The file is the basic unit of storage for many operating systems. • Although C does not have any built-in method for performing file I/O, the C standard library contains a very rich set of I/O functions providing and efficient, powerful and flexible approach. • Those functions can read or write any type of data to files. 3
  • 4. What is a File? • In C, a file can refer to a disk file and every disk file has a name. • Filenames are stored as strings, just like other text data. • In DOS and Windows 3.X, a complete filename consists of a name that has from one to eight characters, optionally followed by a period and an extension that has from one to three characters. • In contrast, the Windows 95 and Windows NT OS, as well as most UNIX systems, permit filenames upto 256 characters long. 4
  • 5. What is a File? (Cont…) • A file name in C program also can contain path information. • The path specifies the drive and or directory where the file is located. ▫ C:DATAlist.txt  this is a good programming practice to specify path information. is used to separate the directory names in the path. • If you specify a filename without a path, it will be assumed that the file is located at whatever location the OS currently designates as the default. char* filename = “C:DATAlist.txt”; 5
  • 6. What is a Stream? • The data flow you transfer from your program to a file, or vice versa, is called a stream which is a series of bytes. • Hence, a stream is a sequence of bytes travelling from a source to a destination over a communication medium. • Streams can either be input or output. • The input stream is used for reading while the output stream is used for writing. • Unlike a file, which targets a specific I/O device, a stream is device independent. • You can perform I/O operations to any type of file by simply associating a stream to the file. 6
  • 7. What is a Stream? (Cont…) • There are two formats of streams. • Text streams ▫ Consists of sequence of characters. ▫ Depending on the system, each line of characters in a text stream may be terminated by a newline character. ▫ Text streams are used for textual data, which has a consistent appearance from one environment to another, or from one machine to another. 7
  • 8. What is a Stream? (Cont…) • Binary stream ▫ It consists of series of bytes, e.g., the contents of an executable program file. ▫ Binary streams are primarily used for nentextual data, where the exact contents of the data are maintained without regard to appearance. 8
  • 9. Buffered I/O • In C, a memory area that is temporarily used to store data before it is sent to its destination is called a buffer. • With the help of buffers, the operating system can improve efficiency by reducing the number of accesses to I/O devices (that is files). • Access to a disk or other I/O device is generally much slower than direct access to memory. • Several I/O operations can be performed on a buffer that represents the I/O file, instead of the file itself. • e.g. if several write operations are sent to a buffer, they are kept in memory until it is time to save, or commit, the new data to the actual device. 9
  • 10. Pointers of FILE • The FILE structure is the file control structure defined in the header file stdio.h. • A pointer of type FILE is called a file pointer, which references a disk file. • A file pointer is used by a stream to conduct the operation of the I/O function. • e.g. following defines a file pointer called fptr; FILE *fptr; 10
  • 11. Opening a File • fopen() opens a file and associates a stream with the opened file. #include <stdio.h> FILE *fopen( const char* filename, const char *mode); • Here, filename is a char pointer that references a string containing a filename. • Mode points to another string that specifies the way to open the file. • The fopen() function returns a pointer of type FILE in a success scenario otherwise null pointer is returned. 11
  • 12. Opening a File (Cont…) 12 Mode Description r Opens an existing text file for reading purpose. w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. r+ Opens a text file for both reading and writing. w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
  • 13. Opening a File (Cont…) 13 Mode Description rb Opens an existing binary file for reading wb Creates a binary file for writing ab Opens an existing binary file for appending r+b or rb+ Opens an existing binary file for reading or writing w+b or wb+ Creates a binary file for reading or writing a+b ab+ Opens or creates a binary file for appending
  • 14. Opening a File (Cont…) #include <stdio.h> int main () { FILE *fptr; fptr = fopen("test.txt","r"); if (fptr == NULL ) { printf("Cannot open file.n"); exit (1); } else { printf("File opens successfully.n"); } return 0; } 14
  • 15. Closing a File • After a disk file is read, written or appended with some new data, you have to disassociate the file from a specified stream by calling the fclose() function. #include <stdio.h> int fclose ( FILE *stream ); • Here stream is a file pointer that is associated with a stream to the opened file. • If fclose() closes a file successfully, it returns 0, otherwise it returns EOF. • Normally, fclose() fails only when the disk is removed before the function is called or there is no more space left on the disk. • The fclose() flushes data left in the buffer to ensure that no data will be lost before it disassociates a specified stream with the opened file. 15
  • 16. Closing a File (Cont…) #include <stdio.h> int main () { FILE *fptr; fptr = fopen("test.txt","r"); if (fptr == NULL ) { printf("Cannot open file.n"); exit (1); } 16
  • 17. Closing a File (Cont…) else { int status = 0; printf("File opens successfully.n"); status = fclose(fptr); if (status == 0 ) printf("Status: %i - File closed successfully.n", status); else printf("Error in file closing.n"); } return 0; } 17
  • 18. I/O Operations • In C, you can perform I/O operations in the following ways; ▫ Read or write one character at a time. ▫ Read or write one line of text at a time. ▫ Read or write one block of characters at a time. 18
  • 19. Read One Character at a Time • fgetc() fucntion is used to read one character at a time. #include <stdio.h> int fgetc( FILE *stream); • Here stream is the file pointer associated with a stream. • The fgetc() fetches the next character from the stream. • The function then returns value of an int that is converted from the character. • EOF is returned if fgetc() encounters the end of file or if there is an error. 19
  • 20. Read One Character at a Time (Cont…) #include <stdio.h> int main () { FILE *fptr; char fileName [] = "test.txt"; if ( (fptr = fopen (fileName, "r")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ int c; while ( (c = fgetc(fptr))!= EOF){ putchar (c); } fclose(fptr); } return 0; } 20
  • 21. Write One Character at a Time • fputc() fucntion is used to write one character at a time. #include <stdio.h> int fputc (int c, FILE *stream); • Here c is an int value that represents a character. • In fact, the int value is converted to an unsigned char before being output. • Stream is the file pointer associated with a stream. • The fputc() returns the character written if the function is successful; otherwise, it returns EOF. • After a character is written, the fputc() advances the associated file pointer. 21
  • 22. Write One Character at a Time (Cont…) #include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("writec.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) { fputc(ch, fp); } fclose(fp); return(0); } 22
  • 23. Write One Character at a Time (Cont…) #include <stdio.h> #include <string.h> int main () { FILE *fptr; char fileName [] = "writec.txt"; char text[100] = "This content to be written in to a file"; int lstr = strlen( text ); if ( (fptr = fopen (fileName, "w+")) == NULL) { printf("Cannot open file.n"); exit (1); } 23
  • 24. Write One Character at a Time (Cont…) else { int i; for(i = 0 ; i <= lstr ; i++) fputc (text[i],fptr); printf("End"); fclose(fptr); } return 0; } 24
  • 25. Activity #include <stdio.h> void charReadWrite( FILE*, FILE*); int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL){ printf("Cannot open %s file.n", fileName1); exit (1); } else{ 25
  • 26. Activity if ( (fptr2 = fopen (fileName2, "r")) == NULL){ printf("Cannot open %s file.n", fileName2); exit (1); } else{ charReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 26
  • 27. Activity void charReadWrite( FILE *fin, FILE *fout) { int c; while ((c = fgetc(fin)) != EOF) { fputc(c, fout); putchar(c); } } 27
  • 28. Read One Line of Text at a Time • fgets() function is used to read one line at a time. #include <stdio.h> char *fgets (char *s, int n, FILE *stream); • Here s refers a character array that us used to store characters read from the opened file pointed to by the file pointer stream. • n specifies the maximum number of array elements. • If it is successful, the fgets() function returns a char pointer s. • If EOF is encountered, the fgets() function returns a null pointer and leaves the array untouched. • If an error occurs, the function returns a null pointer, and the contents of the array are unknown. 28
  • 29. Read One Line of Text at a Time (Cont…) #include <stdio.h> int main () { FILE *fptr; char fileName [] = "test.txt"; if ( (fptr = fopen (fileName, "r")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ char buff [80]; while ( fgets(buff, 80, fptr)!= NULL){ printf("%s", buff); } fclose(fptr); } return 0; } 29
  • 30. Read One Line of Text at a Time (Cont…) • The fgets() can read up to n-1 characters, and can append a null character after the last character fetched, until a newline or and EOF is encountered. • Note that the new line is encountered during the read operation, the fgets() function includes the newline in the array. • This is different from what the gets() does. • The gets() just replaces the newline character with a null character. 30
  • 31. Write One Line of Text at a Time • fputs() function is used to write one line at a time. #include <stdio.h> char *fputs (const char *s, FILE *stream); • Here s points to the array that contains the characters to be written to a file associated with the file pointer stream. • The const modifier indicates that the content of the array pointed to by s cannot be changed by the fputs(). • If it is fails, the fputs() function returns a nonzero value; otherwise, it returns zero. 31
  • 32. Write One Line of Text at a Time (Cont…) • Note that the character array must include a null character at the end of the string as the terminator to the fputs(). • Also, unlike the puts(), the fputs() does not insert a newline character to the string written to the file. 32
  • 33. Write One Line of Text at a Time (Cont…) #include <stdio.h> #include <string.h> int main () { FILE *fptr; char fileName [] = "writec.txt"; char text[100] = "This content to be written in to a filen"; int lstr = strlen( text ); if ( (fptr = fopen (fileName, "w+")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ int i=0; for(;i<10;i++) fputs(text, fptr); fclose(fptr); } return 0; } 33
  • 34. Activity #include <stdio.h> void lineReadWrite( FILE*, FILE*); const int MAX_LEN = 81; int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL) { printf("Cannot open %s file.n", fileName1); } 34
  • 35. Activity else { if ( (fptr2 = fopen (fileName2, "r")) == NULL) { printf("Cannot open %s file.n", fileName2); } else { lineReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 35
  • 36. Activity void lineReadWrite( FILE *fin, FILE *fout) { char buff[100]; while ( fgets(buff, MAX_LEN, fin) != NULL) { fputs(buff, fout); printf( "%s", buff); } } 36
  • 37. Read One Block of Text at a Time • fread() is used to reading one block of text at a time. #include <stdio.h> size_t fread ( void *ptr, size_t size, size_t n, FILE *stream); • Here ptr is a pointer to an array in which the data is stored. • Size indicates the size of each array element. • N specifies the number of elements to read. • Stream is a file pointer that is associated with the opened file for reading. • size_t is a integral type of defined in the header file stdio.h. • The fread() returns the number of elements actually read. 37
  • 38. Read One Block of Text at a Time (Cont…) • The number of elements read by the fread() function should be equal to the value specified by the third argument to the function, unless an error occurs or and EOF is encountered. • The fread() returns the number of elements that are actually read during the attempt, if an error occurs or an EOF is encountered. 38
  • 39. Write One Block of Text at a Time • fwrite() is used to write one block of text at a time. #include <stdio.h> size_t fwrite( const void *ptr, size_t size, size_t n,FILE *stream); • Here ptr references the array that contains the data to be written to an opened file pointed to by the file pointer stream. • size indicates the size of each element in the array. • n specifies the number of elements to be written. • The fwrite() function returns the number of elements actually written. • If no error has occurred, the value written by fwrite() should equal the third argument in the function. • The return value may be less than the specified value in an error occurs. 39
  • 40. Write One Block of Text at a Time (Cont…) • Note that it is programmers’ responsibility to ensure that the array is large enough to hold data for either the fread() or the fwrite(). • In C, a function called feof() can be used to determine when the end of a file is encountered. #include <stdio.h> int feof(FILE *stream); • The feof() returns 0 if the end of the file has not been reached; otherwise, it returns the non zero integer. 40
  • 41. Write One Block of Text at a Time (Cont…) #include <stdio.h> #include <string.h> int main() { FILE *fp; char c[] = "This is about fread() and fwrite()"; char buffer[100]; /* Open file for both reading and writing */ fp = fopen("file.txt", "w+"); /* Write data to the file */ fwrite(c, strlen(c) + 1, 1, fp); 41
  • 42. Write One Block of Text at a Time (Cont…) /* Seek to the beginning of the file */ fseek(fp, 0, SEEK_SET); /* Read and display data */ fread(buffer, strlen(c)+1, 1, fp); printf("%sn", buffer); fclose(fp); return(0); } 42
  • 43. Activity #include <stdio.h> void blockReadWrite( FILE*, FILE*); const int MAX_LEN = 81; int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL) { printf("Cannot open %s file.n", fileName1); } 43
  • 44. Activity else { if ( (fptr2 = fopen (fileName2, "r")) == NULL) { printf("Cannot open %s file.n", fileName2); } else { blockReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 44
  • 45. Activity void blockReadWrite( FILE *fin, FILE *fout) { int num; char buff[100]; while (!feof(fin)) { num = fread(buff, sizeof(char), MAX_LEN, fin); buff[num * sizeof(char)] = '0'; printf( "%s", buff); fwrite(buff, sizeof(char), num,fout); } } 45
  • 46. Objective Re-cap • Now you should be able to: ▫ Define the C standard functions for managing file input output. ▫ Apply taught concepts for writing programs. 46
  • 47. References • Chapter 16 - Programming in C, 3rd Edition, Stephen G. Kochan 47
  • 48. End of COM1407 Next: Data Structures & Algorithms, Compute Graphics & Image Processing 48