SlideShare a Scribd company logo
Jagannath Institute of Management Sciences
Vasant Kunj-II, New Delhi - 110070
Subject Name: Programming In C
Department of Information Technology
Created By: Dr. Arpana Chaturvedi
@Dr. Arpana Chaturvedi
Subject: Programming In C
Topic: Unit III- Part II
Concept of Files
@Dr. Arpana Chaturvedi
Topics to be Covered
▰ Concept of Files
▰ File opening in various modes and closing of a file
▰ Unformatted Input and Output Functions
▰ Formatted Input Output Functions
▰ Reading from a Binary file
▰ Writing onto a Binary file
Concept of Files in C
@Dr. Arpana Chaturvedi
Concept of Files in C
@Dr. Arpana Chaturvedi
▰ A file is an external collection of related data treated as a single unit.
▰ The primary purpose of a file is to keep a record of data.
▰ Since the contents of primary memory are lost when the computer is shut
down, we need files to store our data in a more permanent form.
▰ Hence we say, File is a collection of bytes that is stored on secondary storage
devices like disk
Why we need Files in C
@Dr. Arpana Chaturvedi
▰ When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
▰ If you have to enter a large number of data, it will take a lot of time to enter
them all.
▰ However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
▰ You can easily move your data from one computer to another without any
changes.
A file is an external
collection of related data treated as a unit.
Streams in C
@Dr. Arpana Chaturvedi
Data is input to and output from a stream. A stream can be
associated with a physical device, such as a terminal, or with
a file stored in auxiliary memory.
Standard Streams Of Files in C
@Dr. Arpana Chaturvedi
Standard stream names have
already been declared in the stdio.h header
file and cannot be declared again in our program.
There is no need to open and close the standard streams.
It is done automatically by the operating system.
Types of Files in C
@Dr. Arpana Chaturvedi
Types of Files in C
@Dr. Arpana Chaturvedi
There are two kinds of files in a system. They are:
▰ Text files (ASCII)
▰ Binary files
Text Files
▰ Text files contain ASCII codes of digits, alphabetic and symbols.
▰ Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
▰ When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
▰ They take minimum effort to maintain, are easily readable, and provide the
least security and takes bigger storage space.
Types of Files in C
@Dr. Arpana Chaturvedi
Binary Files
▰ Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled
version of text files.
▰ Binary files are mostly the .bin files in your computer.
▰ Instead of storing data in plain text, they store it in the binary form (0's and 1's).
▰ They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
Difference between Types of Files in C
@Dr. Arpana Chaturvedi
Text File Binary File
Bits represent character. Bits represent a custom data.
Less prone to get corrupt as changes reflect as
soon as the file is opened and can easily be
undone.
Can easily get corrupted, even a single bit
change may corrupt the file.
Can store only plain text in a file.
Can store different types of data (image, audio,
text) in a single file.
Widely used file format and can be opened
using any simple text editor.
Developed especially for an application and
may not be understood by other applications.
Mostly .txt and .rtf are used as extensions to
text files.
Can have any application defined extension.
Binary and Text Files in C
Text files store data as a sequence of characters; binary files
store data as they are stored in primary memory.
Categories of Operations of Files in C
@Dr. Arpana Chaturvedi
Categories of Standard Input Output
Functions in C
@Dr. Arpana Chaturvedi
C has eight categories of standard file library functions.
BASIC FILE OPERATIONS IN C
PROGRAMMING
@Dr. Arpana Chaturvedi
Among all 8 Categories, There are 4 main basic operations that can be
performed on any files in C programming language.
▰ Opening/Creating a file
▰ Closing a file
▰ Reading a file
▰ Writing in a file
Opening Files in C
@Dr. Arpana Chaturvedi
Opening/Creating a file:
@Dr. Arpana Chaturvedi
▰ In a C program, we declare a file pointer and use fopen().Opening a file is performed using
the fopen() function defined in the stdio.h header file.
▰ The C library function fopen() is used to open a filename pointed to, by filename using the
given mode to perform operations such as reading, writing etc.
▰ fopen() function creates a new file if the mentioned file name does not exist.
Syntax:
FILE *fopen (const char *filename, const char *mode)
OR
FILE *fp;
fp=fopen (“filename”, ”„mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on
the file. Example: r, w, a, r+, w+ and a+.
Return Value
This function returns a FILE pointer. Otherwise, NULL is
returned and the global variable errno is set to indicate the
error.
File Open Result in C
@Dr. Arpana Chaturvedi
MODE OF OPERATIONS PERFORMED ON
A FILE IN C LANGUAGE:
@Dr. Arpana Chaturvedi
There are many modes in opening a file. Based on the mode of file, it can be opened
for reading or writing or appending the texts.
▰ r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
▰ w – Opens a file in write mode. It returns null if file could not be opened. If file
exists, data are overwritten.
▰ a – Opens a file in append mode. It returns null if file couldn’t be opened.
▰ r+ – Opens a file for read and write mode and sets pointer to the first character in
the file.
▰ w+ – opens a file for read and write mode and sets pointer to the first character
in the file.
▰ a+ – Opens a file for read and write mode and sets pointer to the first character
in the file. But, it can’t modify existing contents.
Different Opening Modes of Files in C
@Dr. Arpana Chaturvedi
Mode Meaning Description
fopen Returns if FILE
Exists Not Exists
r Reading
"r"
Opens a file for reading. The file must exist.
– NULL
w Writing
"w"
Creates an empty file for writing. If a file with
the same name already exists, its content is
erased and the file is considered as a new
empty file.
Over write on Existing Create New File
a Append
"a"
Appends to a file. Writing operations, append
data at the end of the file. The file is created
if it does not exist.
– Create New File
r+ Reading + Writing
"r+"
Opens a file to update both reading and
writing. The file must exist.
New data is written at
the beginning
overwriting existing
data
Create New File
w+ Reading + Writing
"w+"
Creates an empty file for both reading and
writing.
Over write on Existing Create New File
a+ Reading + Appending
"a+"
New data is appended
Create New File
File Opening Modes in C
@Dr. Arpana Chaturvedi
File Opening Modes in C
Example of fopen() in C
@Dr. Arpana Chaturvedi
Output:
@Dr. Arpana Chaturvedi
Closing Files in C
@Dr. Arpana Chaturvedi
Closing a file in C
@Dr. Arpana Chaturvedi
▰ The file (both text and binary) should be closed after reading/writing. Closing a
file is performed using the fclose() function.
Syntax:
▰ int fclose(FILE *fp);
▰ fclose() function closes the file that is being pointed by file pointer fp.
Eg.: In a C program, we close a file as below.
▰ fclose (fp);
Simple Program To Show Use Of Fopen
And Fclose Functions In C
@Dr. Arpana Chaturvedi
Output:
@Dr. Arpana Chaturvedi
Read and Write Operations of Files in C
@Dr. Arpana Chaturvedi
Text and Binary Text File- Read/Write
in C
Formatted input/output, character input/output, and string
input/output functions can be used only with text files.
Block Input and Output in File in C
Unformatted Functions to read from Files in C
@Dr. Arpana Chaturvedi
Unformatted Function to Read From The
File
@Dr. Arpana Chaturvedi
1. fgetc(): It is the simplest function to read a single character from a file.
Syntax:
int fgetc( FILE * fp );
▰ The fgetc() function reads a character from the input file referenced by fp. The
return value is the character read, or in case of any error, it returns EOF.
2. fgets(): The following function allows to read a string from a stream.
Syntax:
char *fgets( char *buf, int n, FILE *fp );
▰ The functions fgets() reads up to n-1 characters from the input stream referenced
by fp. It copies the read string into the buffer buf, appending a null character to
terminate the string.
▰ If this function encounters a newline character 'n' or the end of the file EOF before
they have read the maximum number of characters, then it returns only the
characters read up to that point including the new line character
fgetc()::
@Dr. Arpana Chaturvedi
▰ Description
▰ The C library function int fgetc(FILE *stream) gets the next character (an
unsigned char) from the specified stream and advances the position indicator
for the stream.
▰ Declaration
▰ Following is the declaration for fgetc() function.
▰ int fgetc(FILE *stream)
▰ Parameters
▰ • stream − This is the pointer to a FILE object that identifies the stream on
which the operation is to be performed.
▰ Return Value
▰ This function returns the character read as an unsigned char cast to an int or
EOF on end of file or error.
Output:
@Dr. Arpana Chaturvedi
Unformatted Input Function to Read a File:
in C
@Dr. Arpana Chaturvedi
▰ gets() function
▰ The gets() function enables the user to enter some characters followed by the
enter key.
▰ All the characters entered by the user get stored in a character array.
▰ The null character is added to the array to make it a string.
▰ The gets() allows the user to enter the space-separated strings. It returns the
string entered by the user.
▰ Syntax:
▰ char[] gets(char[]);
Unformatted Input Function to Read a File:
in C
@Dr. Arpana Chaturvedi
1. fgets():
The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the
specified stream and stores it into the string pointed to by str. It stops when either (n-1)
characters are read, the newline character is read, or the end-of-file is reached,
whichever comes first.
Syntax:
▰ char *fgets(char *str, int n, FILE *stream)
Parameters
▰ str − This is the pointer to an array of chars where the string read is stored.
▰ n − This is the maximum number of characters to be read (including the final null-
character). Usually, the length of the array passed as str is used.
▰ stream − This is the pointer to a FILE object that identifies
Return Value
On success, the function returns the same str
parameter. If the End-of-File is encountered
and no characters have been read, the
contents of str remain unchanged and a null
pointer is returned.
If an error occurs, a null pointer is returned.
Example of fgets():
@Dr. Arpana Chaturvedi
Program to find the number of characters,
lines, spaces from a file in C
@Dr. Arpana Chaturvedi
Unformatted Input Function to Read a File:
in C
@Dr. Arpana Chaturvedi
Unformatted Functions to Write in Files in C
@Dr. Arpana Chaturvedi
Unformatted Functions to Write into a file
@Dr. Arpana Chaturvedi
1. fputc(): It is the simplest function to write individual characters to a stream.
Syntax:
▰ int fputc( int c, FILE *fp );
▰ The function fputc() writes the character value of the argument c to the output
stream referenced by fp. It returns the written character written on success
otherwise EOF if there is an error.
2. fputs(): To write a null-terminated string to a stream fputs() function is used.
Syntax:
▰ int fputs( const char *s, FILE *fp );
▰ The function fputs() writes the string s to the output stream referenced by fp.
▰ It returns a non-negative value on success,
Otherwise EOF is returned in case of any error.
C program which copies one file to another.
@Dr. Arpana Chaturvedi
C Program Which Copies One File To
Another.
@Dr. Arpana Chaturvedi
C Program Which Copies One File To
Another.
@Dr. Arpana Chaturvedi
C Program Which Copies One File To
Another.
@Dr. Arpana Chaturvedi
Writing And The Reading From The File
Characters Entered.
@Dr. Arpana Chaturvedi
Writing And The Reading From The File
Characters Entered.
@Dr. Arpana Chaturvedi
Thank You !!
@ Dr.Arpana Chaturvedi

More Related Content

What's hot

Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
Viva
VivaViva
Lexyacc
LexyaccLexyacc
Lexyacc
unifesptk
 
Spark
SparkSpark
A short tutorial on r
A short tutorial on rA short tutorial on r
A short tutorial on r
Ashraf Uddin
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data types
bad_zurbic
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
JK Knowledge
 
R Programming Language
R Programming LanguageR Programming Language
R Programming Language
NareshKarela1
 
1 R Tutorial Introduction
1 R Tutorial Introduction1 R Tutorial Introduction
1 R Tutorial Introduction
Sakthi Dasans
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
sumitbardhan
 
Lex
LexLex
Lexical analysis-using-lex
Lexical analysis-using-lexLexical analysis-using-lex
Lexical analysis-using-lex
Dattatray Gandhmal
 
Lex & yacc
Lex & yaccLex & yacc
Lex & yacc
Taha Malampatti
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
Vasavi College of Engg
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
J'tong Atong
 
Sparql semantic information retrieval by
Sparql semantic information retrieval bySparql semantic information retrieval by
Sparql semantic information retrieval by
IJNSA Journal
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
Ranel Padon
 
R language
R languageR language
R language
Kìshør Krîßh
 

What's hot (19)

Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Viva
VivaViva
Viva
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Spark
SparkSpark
Spark
 
A short tutorial on r
A short tutorial on rA short tutorial on r
A short tutorial on r
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data types
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
R Programming Language
R Programming LanguageR Programming Language
R Programming Language
 
1 R Tutorial Introduction
1 R Tutorial Introduction1 R Tutorial Introduction
1 R Tutorial Introduction
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
 
Lex
LexLex
Lex
 
Lexical analysis-using-lex
Lexical analysis-using-lexLexical analysis-using-lex
Lexical analysis-using-lex
 
Lex & yacc
Lex & yaccLex & yacc
Lex & yacc
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
Sparql semantic information retrieval by
Sparql semantic information retrieval bySparql semantic information retrieval by
Sparql semantic information retrieval by
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 1)
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
 
R language
R languageR language
R language
 

Similar to File Handling in C Part I

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
File management
File managementFile management
File management
sumathiv9
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
samkinggraphics19
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
File handling in c
File handling in cFile handling in c
File handling in c
David Livingston J
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
S P Sajjan
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
Osmania University
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
eShikshak
 

Similar to File Handling in C Part I (20)

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Python-files
Python-filesPython-files
Python-files
 
File management
File managementFile management
File management
 
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptxPOWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
POWER POINT FILE INPUT AND OUTPUT PRESENTATION.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
File handling in c
File handling in cFile handling in c
File handling in c
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 

More from Arpana Awasthi

Unit 5 Part 1 Macros
Unit 5 Part 1 MacrosUnit 5 Part 1 Macros
Unit 5 Part 1 Macros
Arpana Awasthi
 
Unit 2 Part 1.2 Data Types.pdf
Unit 2 Part 1.2 Data Types.pdfUnit 2 Part 1.2 Data Types.pdf
Unit 2 Part 1.2 Data Types.pdf
Arpana Awasthi
 
Introduction To Python.pdf
Introduction To Python.pdfIntroduction To Python.pdf
Introduction To Python.pdf
Arpana Awasthi
 
Unit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfUnit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdf
Arpana Awasthi
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
Eclipse - GUI Palette
Eclipse - GUI Palette Eclipse - GUI Palette
Eclipse - GUI Palette
Arpana Awasthi
 
Machine Learning: Need of Machine Learning, Its Challenges and its Applications
Machine Learning: Need of Machine Learning, Its Challenges and its ApplicationsMachine Learning: Need of Machine Learning, Its Challenges and its Applications
Machine Learning: Need of Machine Learning, Its Challenges and its Applications
Arpana Awasthi
 
Programming language
Programming languageProgramming language
Programming language
Arpana Awasthi
 
Role of machine learning in detection, prevention and treatment of cancer
Role of machine learning in detection, prevention and treatment of cancerRole of machine learning in detection, prevention and treatment of cancer
Role of machine learning in detection, prevention and treatment of cancer
Arpana Awasthi
 

More from Arpana Awasthi (9)

Unit 5 Part 1 Macros
Unit 5 Part 1 MacrosUnit 5 Part 1 Macros
Unit 5 Part 1 Macros
 
Unit 2 Part 1.2 Data Types.pdf
Unit 2 Part 1.2 Data Types.pdfUnit 2 Part 1.2 Data Types.pdf
Unit 2 Part 1.2 Data Types.pdf
 
Introduction To Python.pdf
Introduction To Python.pdfIntroduction To Python.pdf
Introduction To Python.pdf
 
Unit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfUnit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdf
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
 
Eclipse - GUI Palette
Eclipse - GUI Palette Eclipse - GUI Palette
Eclipse - GUI Palette
 
Machine Learning: Need of Machine Learning, Its Challenges and its Applications
Machine Learning: Need of Machine Learning, Its Challenges and its ApplicationsMachine Learning: Need of Machine Learning, Its Challenges and its Applications
Machine Learning: Need of Machine Learning, Its Challenges and its Applications
 
Programming language
Programming languageProgramming language
Programming language
 
Role of machine learning in detection, prevention and treatment of cancer
Role of machine learning in detection, prevention and treatment of cancerRole of machine learning in detection, prevention and treatment of cancer
Role of machine learning in detection, prevention and treatment of cancer
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 

File Handling in C Part I

  • 1. Jagannath Institute of Management Sciences Vasant Kunj-II, New Delhi - 110070 Subject Name: Programming In C Department of Information Technology Created By: Dr. Arpana Chaturvedi @Dr. Arpana Chaturvedi
  • 2. Subject: Programming In C Topic: Unit III- Part II Concept of Files @Dr. Arpana Chaturvedi
  • 3. Topics to be Covered ▰ Concept of Files ▰ File opening in various modes and closing of a file ▰ Unformatted Input and Output Functions ▰ Formatted Input Output Functions ▰ Reading from a Binary file ▰ Writing onto a Binary file
  • 4. Concept of Files in C @Dr. Arpana Chaturvedi
  • 5. Concept of Files in C @Dr. Arpana Chaturvedi ▰ A file is an external collection of related data treated as a single unit. ▰ The primary purpose of a file is to keep a record of data. ▰ Since the contents of primary memory are lost when the computer is shut down, we need files to store our data in a more permanent form. ▰ Hence we say, File is a collection of bytes that is stored on secondary storage devices like disk
  • 6. Why we need Files in C @Dr. Arpana Chaturvedi ▰ When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. ▰ If you have to enter a large number of data, it will take a lot of time to enter them all. ▰ However, if you have a file containing all the data, you can easily access the contents of the file using a few commands in C. ▰ You can easily move your data from one computer to another without any changes. A file is an external collection of related data treated as a unit.
  • 7. Streams in C @Dr. Arpana Chaturvedi Data is input to and output from a stream. A stream can be associated with a physical device, such as a terminal, or with a file stored in auxiliary memory.
  • 8. Standard Streams Of Files in C @Dr. Arpana Chaturvedi Standard stream names have already been declared in the stdio.h header file and cannot be declared again in our program. There is no need to open and close the standard streams. It is done automatically by the operating system.
  • 9. Types of Files in C @Dr. Arpana Chaturvedi
  • 10. Types of Files in C @Dr. Arpana Chaturvedi There are two kinds of files in a system. They are: ▰ Text files (ASCII) ▰ Binary files Text Files ▰ Text files contain ASCII codes of digits, alphabetic and symbols. ▰ Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad. ▰ When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents. ▰ They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space.
  • 11. Types of Files in C @Dr. Arpana Chaturvedi Binary Files ▰ Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text files. ▰ Binary files are mostly the .bin files in your computer. ▰ Instead of storing data in plain text, they store it in the binary form (0's and 1's). ▰ They can hold a higher amount of data, are not readable easily, and provides better security than text files.
  • 12. Difference between Types of Files in C @Dr. Arpana Chaturvedi Text File Binary File Bits represent character. Bits represent a custom data. Less prone to get corrupt as changes reflect as soon as the file is opened and can easily be undone. Can easily get corrupted, even a single bit change may corrupt the file. Can store only plain text in a file. Can store different types of data (image, audio, text) in a single file. Widely used file format and can be opened using any simple text editor. Developed especially for an application and may not be understood by other applications. Mostly .txt and .rtf are used as extensions to text files. Can have any application defined extension.
  • 13. Binary and Text Files in C Text files store data as a sequence of characters; binary files store data as they are stored in primary memory.
  • 14. Categories of Operations of Files in C @Dr. Arpana Chaturvedi
  • 15. Categories of Standard Input Output Functions in C @Dr. Arpana Chaturvedi C has eight categories of standard file library functions.
  • 16. BASIC FILE OPERATIONS IN C PROGRAMMING @Dr. Arpana Chaturvedi Among all 8 Categories, There are 4 main basic operations that can be performed on any files in C programming language. ▰ Opening/Creating a file ▰ Closing a file ▰ Reading a file ▰ Writing in a file
  • 17. Opening Files in C @Dr. Arpana Chaturvedi
  • 18. Opening/Creating a file: @Dr. Arpana Chaturvedi ▰ In a C program, we declare a file pointer and use fopen().Opening a file is performed using the fopen() function defined in the stdio.h header file. ▰ The C library function fopen() is used to open a filename pointed to, by filename using the given mode to perform operations such as reading, writing etc. ▰ fopen() function creates a new file if the mentioned file name does not exist. Syntax: FILE *fopen (const char *filename, const char *mode) OR FILE *fp; fp=fopen (“filename”, ”„mode”); Where, fp – file pointer to the data type “FILE”. filename – the actual file name with full path of the file. mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Return Value This function returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.
  • 19. File Open Result in C @Dr. Arpana Chaturvedi
  • 20. MODE OF OPERATIONS PERFORMED ON A FILE IN C LANGUAGE: @Dr. Arpana Chaturvedi There are many modes in opening a file. Based on the mode of file, it can be opened for reading or writing or appending the texts. ▰ r – Opens a file in read mode and sets pointer to the first character in the file. It returns null if file does not exist. ▰ w – Opens a file in write mode. It returns null if file could not be opened. If file exists, data are overwritten. ▰ a – Opens a file in append mode. It returns null if file couldn’t be opened. ▰ r+ – Opens a file for read and write mode and sets pointer to the first character in the file. ▰ w+ – opens a file for read and write mode and sets pointer to the first character in the file. ▰ a+ – Opens a file for read and write mode and sets pointer to the first character in the file. But, it can’t modify existing contents.
  • 21. Different Opening Modes of Files in C @Dr. Arpana Chaturvedi Mode Meaning Description fopen Returns if FILE Exists Not Exists r Reading "r" Opens a file for reading. The file must exist. – NULL w Writing "w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file. Over write on Existing Create New File a Append "a" Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist. – Create New File r+ Reading + Writing "r+" Opens a file to update both reading and writing. The file must exist. New data is written at the beginning overwriting existing data Create New File w+ Reading + Writing "w+" Creates an empty file for both reading and writing. Over write on Existing Create New File a+ Reading + Appending "a+" New data is appended Create New File
  • 22. File Opening Modes in C @Dr. Arpana Chaturvedi
  • 24. Example of fopen() in C @Dr. Arpana Chaturvedi
  • 26. Closing Files in C @Dr. Arpana Chaturvedi
  • 27. Closing a file in C @Dr. Arpana Chaturvedi ▰ The file (both text and binary) should be closed after reading/writing. Closing a file is performed using the fclose() function. Syntax: ▰ int fclose(FILE *fp); ▰ fclose() function closes the file that is being pointed by file pointer fp. Eg.: In a C program, we close a file as below. ▰ fclose (fp);
  • 28. Simple Program To Show Use Of Fopen And Fclose Functions In C @Dr. Arpana Chaturvedi
  • 30. Read and Write Operations of Files in C @Dr. Arpana Chaturvedi
  • 31. Text and Binary Text File- Read/Write in C Formatted input/output, character input/output, and string input/output functions can be used only with text files.
  • 32. Block Input and Output in File in C
  • 33. Unformatted Functions to read from Files in C @Dr. Arpana Chaturvedi
  • 34. Unformatted Function to Read From The File @Dr. Arpana Chaturvedi 1. fgetc(): It is the simplest function to read a single character from a file. Syntax: int fgetc( FILE * fp ); ▰ The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. 2. fgets(): The following function allows to read a string from a stream. Syntax: char *fgets( char *buf, int n, FILE *fp ); ▰ The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. ▰ If this function encounters a newline character 'n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character
  • 35. fgetc():: @Dr. Arpana Chaturvedi ▰ Description ▰ The C library function int fgetc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. ▰ Declaration ▰ Following is the declaration for fgetc() function. ▰ int fgetc(FILE *stream) ▰ Parameters ▰ • stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed. ▰ Return Value ▰ This function returns the character read as an unsigned char cast to an int or EOF on end of file or error.
  • 37. Unformatted Input Function to Read a File: in C @Dr. Arpana Chaturvedi ▰ gets() function ▰ The gets() function enables the user to enter some characters followed by the enter key. ▰ All the characters entered by the user get stored in a character array. ▰ The null character is added to the array to make it a string. ▰ The gets() allows the user to enter the space-separated strings. It returns the string entered by the user. ▰ Syntax: ▰ char[] gets(char[]);
  • 38. Unformatted Input Function to Read a File: in C @Dr. Arpana Chaturvedi 1. fgets(): The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first. Syntax: ▰ char *fgets(char *str, int n, FILE *stream) Parameters ▰ str − This is the pointer to an array of chars where the string read is stored. ▰ n − This is the maximum number of characters to be read (including the final null- character). Usually, the length of the array passed as str is used. ▰ stream − This is the pointer to a FILE object that identifies Return Value On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned.
  • 39. Example of fgets(): @Dr. Arpana Chaturvedi
  • 40. Program to find the number of characters, lines, spaces from a file in C @Dr. Arpana Chaturvedi
  • 41. Unformatted Input Function to Read a File: in C @Dr. Arpana Chaturvedi
  • 42. Unformatted Functions to Write in Files in C @Dr. Arpana Chaturvedi
  • 43. Unformatted Functions to Write into a file @Dr. Arpana Chaturvedi 1. fputc(): It is the simplest function to write individual characters to a stream. Syntax: ▰ int fputc( int c, FILE *fp ); ▰ The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. 2. fputs(): To write a null-terminated string to a stream fputs() function is used. Syntax: ▰ int fputs( const char *s, FILE *fp ); ▰ The function fputs() writes the string s to the output stream referenced by fp. ▰ It returns a non-negative value on success, Otherwise EOF is returned in case of any error.
  • 44. C program which copies one file to another. @Dr. Arpana Chaturvedi
  • 45. C Program Which Copies One File To Another. @Dr. Arpana Chaturvedi
  • 46. C Program Which Copies One File To Another. @Dr. Arpana Chaturvedi
  • 47. C Program Which Copies One File To Another. @Dr. Arpana Chaturvedi
  • 48. Writing And The Reading From The File Characters Entered. @Dr. Arpana Chaturvedi
  • 49. Writing And The Reading From The File Characters Entered. @Dr. Arpana Chaturvedi
  • 50. Thank You !! @ Dr.Arpana Chaturvedi