SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
A short tutorial on r
A short tutorial on rA short tutorial on r
A short tutorial on rAshraf Uddin
 
Primitive data types
Primitive data typesPrimitive data types
Primitive data typesbad_zurbic
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabusJK Knowledge
 
R Programming Language
R Programming LanguageR Programming Language
R Programming LanguageNareshKarela1
 
1 R Tutorial Introduction
1 R Tutorial Introduction1 R Tutorial Introduction
1 R Tutorial IntroductionSakthi 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-4sumitbardhan
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesVasavi College of Engg
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environmentsJ'tong Atong
 
Sparql semantic information retrieval by
Sparql semantic information retrieval bySparql semantic information retrieval by
Sparql semantic information retrieval byIJNSA 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 ProcessingRanel Padon
 

Mais procurados (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
 

Semelhante a File Handling in C Part I

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
File management
File managementFile management
File managementsumathiv9
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdfsulekha24
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : PointerS P Sajjan
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing fileskeeeerty
 

Semelhante a 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
 
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'
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 

Mais de 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.pdfArpana Awasthi
 
Introduction To Python.pdf
Introduction To Python.pdfIntroduction To Python.pdf
Introduction To Python.pdfArpana Awasthi
 
Unit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfUnit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfArpana Awasthi
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfArpana 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 ApplicationsArpana 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 cancerArpana Awasthi
 

Mais de 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
 

Último

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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