Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input / Output Functions, Character Input / Output Functions, Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files, Converting File Type
This is ppt prsented by me in class in this ppt i include file handling in which i tell us about the types of files
creation of text file in C ++ ,updating a text file in C++ , printing the inforamtion in text file .creation of binary file in C ++ ,updating a binary file in C++ , printing the inforamtion in binary file, text file function and binary file function in c++ , File ponters ,syntax of every thing and use of file pointers and many more.
File is the basic unit of information storage on a secondary storage device. Therefore, almost every form of data and information reside on these devices in form of file – whether audio data or video, whether text or binary.
Files may be classified on different bases as follows:
1. On the basis of content:
Text files: Files containing data/information in textual form. It is merely a collection of characters. Document files etc.
Binary files: Files containing machine code. The contents are non-recognizable and can be interpreted only in a specified way using the same application that created it. E.g. executable program files, audio files, video files etc.
Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input / Output Functions, Character Input / Output Functions, Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files, Converting File Type
This is ppt prsented by me in class in this ppt i include file handling in which i tell us about the types of files
creation of text file in C ++ ,updating a text file in C++ , printing the inforamtion in text file .creation of binary file in C ++ ,updating a binary file in C++ , printing the inforamtion in binary file, text file function and binary file function in c++ , File ponters ,syntax of every thing and use of file pointers and many more.
File is the basic unit of information storage on a secondary storage device. Therefore, almost every form of data and information reside on these devices in form of file – whether audio data or video, whether text or binary.
Files may be classified on different bases as follows:
1. On the basis of content:
Text files: Files containing data/information in textual form. It is merely a collection of characters. Document files etc.
Binary files: Files containing machine code. The contents are non-recognizable and can be interpreted only in a specified way using the same application that created it. E.g. executable program files, audio files, video files etc.
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
File recovery is one of the stages in computer forensic investigative process to identify an
acquired file to be used as digital evident. The recovery is performed on files that have been deleted from
a file system. However, in order to recover a deleted file, some considerations should be taken. A deleted
file is potentially modified from its original condition because another file might either partly or entirely
overriding the file content. A typical approach in recovering deleted file is to apply Boyer-Moore algorithm
that has rather high time complexity in terms of string searching. Therefore, a better string matching
approach for recovering deleted file is required. We propose Aho-Corasick parsing technique to read file
attributes from the master file table (MFT) in order to examine the file condition. If the file was deleted, then
the parser search the file content in order to reconstruct the file. Experiments were conducted using
several file modifications, such as 0% (unmodified), 18.98%, 32.21% and 59.77%. From the experimental
results we found that the file reconstruction process on the file system was performed successfully. The
average successful rate for the file recovery from four experiments on each modification was 87.50% and
for the string matching process average time on searching file names was 0.32 second.
FellowBuddy.com is an innovative platform that brings students together to share notes, exam papers, study guides, project reports and presentation for upcoming exams.
We connect Students who have an understanding of course material with Students who need help.
Benefits:-
# Students can catch up on notes they missed because of an absence.
# Underachievers can find peer developed notes that break down lecture and study material in a way that they can understand
# Students can earn better grades, save time and study effectively
Our Vision & Mission – Simplifying Students Life
Our Belief – “The great breakthrough in your life comes when you realize it, that you can learn anything you need to learn; to accomplish any goal that you have set for yourself. This means there are no limits on what you can be, have or do.”
Like Us - https://www.facebook.com/FellowBuddycom
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
File recovery is one of the stages in computer forensic investigative process to identify an
acquired file to be used as digital evident. The recovery is performed on files that have been deleted from
a file system. However, in order to recover a deleted file, some considerations should be taken. A deleted
file is potentially modified from its original condition because another file might either partly or entirely
overriding the file content. A typical approach in recovering deleted file is to apply Boyer-Moore algorithm
that has rather high time complexity in terms of string searching. Therefore, a better string matching
approach for recovering deleted file is required. We propose Aho-Corasick parsing technique to read file
attributes from the master file table (MFT) in order to examine the file condition. If the file was deleted, then
the parser search the file content in order to reconstruct the file. Experiments were conducted using
several file modifications, such as 0% (unmodified), 18.98%, 32.21% and 59.77%. From the experimental
results we found that the file reconstruction process on the file system was performed successfully. The
average successful rate for the file recovery from four experiments on each modification was 87.50% and
for the string matching process average time on searching file names was 0.32 second.
FellowBuddy.com is an innovative platform that brings students together to share notes, exam papers, study guides, project reports and presentation for upcoming exams.
We connect Students who have an understanding of course material with Students who need help.
Benefits:-
# Students can catch up on notes they missed because of an absence.
# Underachievers can find peer developed notes that break down lecture and study material in a way that they can understand
# Students can earn better grades, save time and study effectively
Our Vision & Mission – Simplifying Students Life
Our Belief – “The great breakthrough in your life comes when you realize it, that you can learn anything you need to learn; to accomplish any goal that you have set for yourself. This means there are no limits on what you can be, have or do.”
Like Us - https://www.facebook.com/FellowBuddycom
Basics
A file has to be opened before a data can be read from or written to it.
Dat is read from a file and then manipulated by program logic.
The output is often written to another file because different functions can read the same file, a common buffer and file position indicator are maintained in memory for function to know how much of the file has already been read.
C supports End of File (EOF) and file related issues
Opening and Closing files
File pointers and Buffers
File read/write function
File Error Handling
Text and Binary File
Reading and Writing binary file
Manipulating file position
Other file handling function
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
File handling in C involves manipulating files through operations such as opening, reading, writing, and closing. The `<stdio.h>` library provides functions like `fopen`, `fclose`, `fread`, and `fwrite` for these operations. To read from a file, you can use functions like `fscanf` or `fgets`, while `fprintf` and `fputs` are used for writing. It's crucial to check for errors during file operations and close files using `fclose` to ensure proper resource management. Binary file handling is possible with functions like `fwrite` and `fread`. File handling is integral for tasks involving data storage, retrieval, and manipulation in C programs.
Wherever there is a need to handle large volumes of data, it is advantageous to store data on the disks and read whenever necessary. This method employs the concept of files to store data. A file is a place on disk where a group of related data is stored.file handling c programming tutorial
This PPT is very much useful for practitioners who are all making products and services to society. Mangers think innovatively and come up with innovative ideas. It is a 5 stage processing also called a design thinking process. The stages are empathize, define, ideate, prototype and test.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Water billing management system project report.pdfKamal Acharya
Our project entitled “Water Billing Management System” aims is to generate Water bill with all the charges and penalty. Manual system that is employed is extremely laborious and quite inadequate. It only makes the process more difficult and hard.
The aim of our project is to develop a system that is meant to partially computerize the work performed in the Water Board like generating monthly Water bill, record of consuming unit of water, store record of the customer and previous unpaid record.
We used HTML/PHP as front end and MYSQL as back end for developing our project. HTML is primarily a visual design environment. We can create a android application by designing the form and that make up the user interface. Adding android application code to the form and the objects such as buttons and text boxes on them and adding any required support code in additional modular.
MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software. It is a stable ,reliable and the powerful solution with the advanced features and advantages which are as follows: Data Security.MySQL is free open source database that facilitates the effective management of the databases by connecting them to the software.
Online aptitude test management system project report.pdfKamal Acharya
The purpose of on-line aptitude test system is to take online test in an efficient manner and no time wasting for checking the paper. The main objective of on-line aptitude test system is to efficiently evaluate the candidate thoroughly through a fully automated system that not only saves lot of time but also gives fast results. For students they give papers according to their convenience and time and there is no need of using extra thing like paper, pen etc. This can be used in educational institutions as well as in corporate world. Can be used anywhere any time as it is a web based application (user Location doesn’t matter). No restriction that examiner has to be present when the candidate takes the test.
Every time when lecturers/professors need to conduct examinations they have to sit down think about the questions and then create a whole new set of questions for each and every exam. In some cases the professor may want to give an open book online exam that is the student can take the exam any time anywhere, but the student might have to answer the questions in a limited time period. The professor may want to change the sequence of questions for every student. The problem that a student has is whenever a date for the exam is declared the student has to take it and there is no way he can take it at some other time. This project will create an interface for the examiner to create and store questions in a repository. It will also create an interface for the student to take examinations at his convenience and the questions and/or exams may be timed. Thereby creating an application which can be used by examiners and examinee’s simultaneously.
Examination System is very useful for Teachers/Professors. As in the teaching profession, you are responsible for writing question papers. In the conventional method, you write the question paper on paper, keep question papers separate from answers and all this information you have to keep in a locker to avoid unauthorized access. Using the Examination System you can create a question paper and everything will be written to a single exam file in encrypted format. You can set the General and Administrator password to avoid unauthorized access to your question paper. Every time you start the examination, the program shuffles all the questions and selects them randomly from the database, which reduces the chances of memorizing the questions.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
6th International Conference on Machine Learning & Applications (CMLA 2024)ClaraZara1
6th International Conference on Machine Learning & Applications (CMLA 2024) will provide an excellent international forum for sharing knowledge and results in theory, methodology and applications of on Machine Learning & Applications.
6th International Conference on Machine Learning & Applications (CMLA 2024)
File Handling and Preprocessor Directives
1. UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
4. Text Book and Reference Book
6/9/2021 3.1 _ File Handling Basics 4
5. Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 5
3.1 _ File Handling Basics
6. File Handling Basics
• So far, the input to the C programs is given from the
prompt / terminal.
• When a program is terminated, the entire input data is
lost.
• Storing in a file will preserve the data even if the program
terminates.
• Also to handle a large number of data, it will take a lot of
time to feed them through the terminal.
• If those data are stored in a file, then it is easy to access
them from the file using the file handling functions in C.
• In C programming, a file represents a sequence of bytes on
the disk where a group of related data is stored.
• All file handling functions are available in <stdio.h> header
file.
6/9/2021 3.1 _ File Handling Basics 6
7. Types of Files
• There are two types of files exists in C
Programming.
• They are:
– Text files
– Binary files
6/9/2021 3.1 _ File Handling Basics 7
8. Text Files
• Text files contain ASCII codes of digits, alphabetic and
symbols.
• Text files are the normal files that can be easily created
using Notepad or any simple text editors with an extension
“.txt”.
• When opening those files, it is possible to see all the
contents as plain text.
• We can easily edit or delete the contents.
• Plus and Minus of Text Files:
– They take minimum effort to maintain (+)
– Easily readable (+)
– provide least security (-)
– takes bigger storage space (-)
6/9/2021 3.1 _ File Handling Basics 8
9. Binary Files
• Instead of storing data in plain text, they store it
in the binary form (0's and 1's).
• Binary files usually have an extension “.bin”.
• Plus and Minus of Binary Files:
– They can hold higher amount of data (-)
– not readable easily (-)
– provides a better security than text files (+)
• For example, given the integer number 12345.
– we could store it as individual characters 1, 2, 3, 4,
and 5, using one byte for each character in text file as
6/9/2021 3.1 _ File Handling Basics 9
10. • 1. Opening a New/Existing file
• 2. Writing data into a file
• 3. Reading data from the file
• 4. Closing a file
Operations on Files
6/9/2021 10
3.1 _ File Handling Basics
11. Opening a New/Existing file
• When working with files, it is mandatory to declare a
pointer of type FILE as below:
• The FILE is a structure data type defined in <stdio.h>.
• This declaration is needed for communication between
the file and program.
• A file should be opened before any operation is being
performed on it.
6/9/2021 3.1 _ File Handling Basics 11
12. Opening a New/Existing file
• The syntax of fopen() is given by,
• In the above format, the arguments “path”
and “mode” are strings.
• The fopen()
– returns a pointer to FILE structure on success
– else it returns NULL.
6/9/2021 3.1 _ File Handling Basics 12
13. Opening a New/Existing file
• Every file on the disk has a name known as
filename.
• The filename can be specified as either
absolute path or relative path.
• In the absolute path, the complete location of
the file is given whereas only partial path is
mentioned in the relative path.
6/9/2021 3.1 _ File Handling Basics 13
14. Opening a New/Existing file
• The file mode specifies the kind of operation performed on the
file.
• The various file modes are given in the following table:
6/9/2021 3.1 _ File Handling Basics 14
16. Create a New File using fopen()
• To create a new text file “file1.txt”, we can open
the file in write mode(“w”) as given below:
• In the above example, suppose the file “file1.txt”
already exist in the location E:CPrograms.
• The fopen() removes all the contents from the
file “file1.txt” and creates a new empty file
named “file1.txt”.
• If “file1.txt”does not exist, new empty file
named “file1.txt” is created.
6/9/2021 3.1 _ File Handling Basics 16
17. Read file contents
• To read the contents of the text file “sample.txt”, we
can open the file in read mode(“r”) as given below:
• In the above example, suppose the text file
“sample.txt” exists in the current working directory.
• The function fopen() opens the file for reading in text
mode.
• The reading mode only allows us to read the file, we
cannot write into the file.
6/9/2021 3.1 _ File Handling Basics 17
18. Difference between Append and Write Mode
• Both write (w) mode and append (a) mode are used to
write data into a file.
• In both the modes, new file is created if it doesn't exist
already.
• The only difference is, when a file is opened in the
write mode, the file is reset, resulting in deletion of
any data already present in the file.
• While in append mode this will not happen.
• Append mode is used to append or add data to the
existing data of file (if any).
• Hence, when a file is opened in append (a) mode, the
file pointer/cursor is positioned at the end of the file.
6/9/2021 3.1 _ File Handling Basics 18
20. Example 2:
char filename[80];
FILE *fp;
printf(“Enter the filename to be opened”);
gets(filename);
fp = fopen(filename,“w”);
6/9/2021 20
3.1 _ File Handling Basics
Example 2
21. • The file should be closed after performing read/write
operation.
• Closing of a file is performed using the function
fclose().
• Closing a file frees the file pointer (file pointer is
disconnected from a file) and associated buffers.
• The fclose() will close the file specified by the fptr
whereas the fcloseall() closes all the files that are
already opened.
• The fclose() function
– returns 0 if close operation is successful or
– returns EOF if an error was encountered.
Closing a File
6/9/2021 21
3.1 _ File Handling Basics
22. Detecting the End-of-File (EOF)
• While performing read and write operations
on files, we do not know exactly how long the
file is.
• Usually, we read data from the beginning to
the end of the file.
• To identify the reach of end-of-file (EOF),
there are two ways available.
6/9/2021 3.1 _ File Handling Basics 22
23. Way 1
• While reading the file in text mode by character
at a time, we can compare the character that has
been read with EOF, which is a symbolic constant
defined in stdio.h whose value is set to -1.
• The following code snippet does that,
6/9/2021 3.1 _ File Handling Basics 23
24. Way 2
• The other way is the use of feof( ) function defined in
stdio.h.
• The syntax of feof( ) is given by:
• The function returns 0 (false) when the end of the file
has not been reached and a non-zero value (true) if
the EOF has been reached.
• A simple code snippet using feof( ) is given as
6/9/2021 3.1 _ File Handling Basics 24
25. • fopen has two important consequences
– creation of a file pointer and file buffer
• File pointer is a variable that points to a structure
typedef to FILE.
• FILE contains the following information related to
the opened file
– The mode of opening.
– The location of the file buffer.
– The file position indicator.
– Whether EOF or any errors have been encountered on
reading or writing.
• File position indicator also called file offset pointer,
plays important role in input/output operations
Detecting the file pointer and file buffer
6/9/2021 25
3.1 _ File Handling Basics
26. • When a file is read with fgetc, data is first sent
from disk to the buffer.
Detecting the file pointer and file buffer
6/9/2021 26
3.1 _ File Handling Basics
27. Example 3:
FILE *fp;
fp = fopen(“data.dat”,“r”);
if(fp == NULL)
{
printf(“Can not open data.datn”);
exit(1);
}
Or
FILE *fp;
if((fp = fopen(“data.dat”, “r”)) ==NULL)
{
printf(“Can not open data.datn”);
exit(1);
}
6/9/2021 27
3.1 _ File Handling Basics
Detecting File Pointer
29. UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
30. Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 30
3.2 _ Reading and Writing Functions in Files
31. Input and Output Operations
• A C program can read data from the keyboard and
writes data into the monitor.
• Similarly, it can read and write from/into the file as
shown in the diagram.
6/9/2021 3.2 _ Reading and Writing Functions in Files 31
32. Input and Output Operations
• A number of functions are available for
performing operations on files.
• They are classified as formatted File I/O and
unformatted File I/O functions.
• The formatted functions deal with all kind of
data whereas the unformatted functions deal
only character data type.
• Different functions are also available for
handling text as well as binary files.
6/9/2021 3.2 _ Reading and Writing Functions in Files 32
33. List of read/input functions
• To perform read operations the following
functions are used.
– fgetc ( )
– fgets ( )
– fscanf ( )
– fread ( )
6/9/2021 3.2 _ Reading and Writing Functions in Files 33
34. List of write/output functions
• To perform read operations the following
functions are used.
– fputc ( )
– fputs ( )
– fprintf ( )
– fwrite ( )
6/9/2021 3.2 _ Reading and Writing Functions in Files 34
35. • Character-oriented functions (fgetc and fputc)
• Line-oriented functions (fgets and fputs)
• Formatted functions (fscanf and fprintf)
• Array- and structure-oriented functions (fread
and fwrite)
• All the functions use the file pointer as
argument and work with any file including
stdin, stdout and stderr.
List of Read/Write functions
6/9/2021 35
3.2 _ Reading and Writing Functions in Files
36. Reading and Writing to a text file using fgetc () and fputc ()
• fgetc () reads the content of the file character by
character.
• After reading a character from the file, fgetc() function
moves the file pointer to next character in the file.
• The fgetc () function returns the next character from
the file specified.
• It returns EOF if end-of-file is reached or error
occurred.
6/9/2021 3.2 _ Reading and Writing Functions in Files 36
37. Example 1
• Assume there is a text file “file1.txt” with the
content “Hello World!” . Write the C program
to read that file one character at a time using
fgetc() function and display it on the monitor.
6/9/2021 3.2 _ Reading and Writing Functions in Files 37
38. 6/9/2021 3.2 _ Reading and Writing Functions in Files 38
39. fputc ( ) function
• The function fputc ( ) writes a character to the
specified file and automatically advances the file
pointer to the next position in the file.
– On success, the written character is returned by the
function.
– If pointer is at end of file or if an error occurs EOF file
is returned by this function.
• Syntax:
– char − This is the character to be written.
– fptr − This is the pointer to a specified file that
indicates where the character is to be written.
6/9/2021 3.2 _ Reading and Writing Functions in Files 39
40. Example 2
• Write a c program to write the string
“Engineers create the World” in the file
sample.txt using fputc() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 40
41. 6/9/2021 3.2 _ Reading and Writing Functions in Files 41
42. Reading and Writing to a text file using fgets () and fputs ()
• The function fgets() is used to read a file line by line.
– str − This is the pointer to an array of characters where
the string read is stored.
– size − This is the maximum number of characters to be
read (including terminating character “0”). Usually, the
length of the array “str” is used.
– fptr − This is the pointer that identifies the file where
characters are read from.
6/9/2021 3.2 _ Reading and Writing Functions in Files 42
43. Reading and Writing to a text file using fgets () and fputs ()
• fgets ( ) reads a line from the specified file and stores
it into the string pointed to by str.
– It stops when (size-1) characters are read or
– the newline character is read, or
– the end-of-file is reached, whichever comes first.
• While all the characters are read without any error, a
null (“ 0” ) character is appended to the end of the
string.
• On success, fgets () returns the same str parameter.
• If end-of-file is encountered or an error occurred, a
NULL value is returned.
6/9/2021 3.2 _ Reading and Writing Functions in Files 43
44. Example 3
• Again consider the text file “file1.txt”. Now,
write a C program to read the file using fgets()
function and read 4 characters at a time and
those are displayed in the monitor.
6/9/2021 3.2 _ Reading and Writing Functions in Files 44
45. 6/9/2021 3.2 _ Reading and Writing Functions in Files 45
46. fputs ( ) function
• This function is used to write a string into the file.
• It has two arguments,
– pointer to string and
– file pointer.
• It writes a null-terminated string to the file.
• The null character is not written to the file.
• On success, fputs( ) returns Non-negative value.
• On error, it returns EOF or Negative value.
• str − This is an array containing a string (terminated by
“0”) to be written into a file.
• fptr − This is the pointer to a specified file that
identifies the stream where the string is to be written.
6/9/2021 3.2 _ Reading and Writing Functions in Files 46
47. Example 4
• Write a C program to write 5 strings into the
file sample.txt using fputs() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 47
48. 6/9/2021 3.2 _ Reading and Writing Functions in Files 48
49. Reading and Writing to a text file using fscanf() and fprintf ()
• For reading and writing to a text file, we use
the functions fscanf() and fprintf() .
• They are just the file versions of scanf()
and printf().
• The only difference is that fscanf() and fprint()
expects a pointer to the structure FILE.
• Other functions like fgetchar(), fputc() etc. can
be used in a similar way.
6/9/2021 3.2 _ Reading and Writing Functions in Files 49
50. fscanf ( ) function
• The functions fgetc ( ) and fgets ( ) are used for
reading only character data.
• But, fscanf ( ) can read different types of data
such as int, float, char, etc., from the given file.
• On success, this function returns the number of
input items successfully matched and assigned
to argument specified.
• On failure, it returns EOF.
6/9/2021 3.2 _ Reading and Writing Functions in Files 50
51. fscanf ( ) function
• The parameters used in the fscanf() are:
– fptr − This is the pointer that identifies the file where
characters are read from.
– format-string – This is a string which controls the
interpretation of the argument list. A format
specification causes the fscanf() function to read and
convert characters in the input into values of a
specified type.
– argument-list - The value read from the file based on
format-string is assigned to an argument in the
argument list.
6/9/2021 3.2 _ Reading and Writing Functions in Files 51
52. Example 5
• Write a C program to Read the integer
number from a file sample.txt using fscanf()
function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 52
53. 6/9/2021 3.2 _ Reading and Writing Functions in Files 53
54. fprintf () function
• Like fscanf( ), the function fprintf( ) handles
different types of data.
• It can be used for writing formatted data into
the file.
• On success, fprintf( ) returns the total number
of bytes written to the file.
• On error, it returns EOF.
6/9/2021 3.2 _ Reading and Writing Functions in Files 54
55. Example 6
• Write a C program to Read the details about n
students from the user and write those
information into the file sample.txt using
fprintf() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 55
56. 6/9/2021 3.2 _ Reading and Writing Functions in Files 56
57. Reading and Writing to a text file using fread() and fwrite ()
• The functions fgetc(), fgets() and fscanf() are used to
read data from text files.
• The function fread() is used to get data from binary
files.
• In binary files, information is stored in the form of
binary and it can be read directly into memory with no
need of any processing to interpret it.
• Hence, handling of files in binary mode is significantly
faster than text mode.
• On success, fread() returns the number of items read
from the file.
• On error or EOF, it returns a number less than “n”.
6/9/2021 3.2 _ Reading and Writing Functions in Files 57
58. fread() function
• Syntax:
– ptr – It is the starting address of the memory block where
data is to be read.
– size – Item size in bytes.
– n- It indicates the maximum number of items read from
the file
– fptr –It specifies the pointer to file from where the data
has to be read.
• The following code snippet discuss about the different
ways in which fread() can be used.
6/9/2021 3.2 _ Reading and Writing Functions in Files 58
59. 6/9/2021 3.2 _ Reading and Writing Functions in Files 59
60. fwrite() function
• fwrite( ) function is used to write binary data into the
file.
• It accepts the same arguments as fread( ).
• Syntax:
• On success, it returns the number of items successfully
written to the file.
• On error, it returns a number less than n.
• The following code snippets show the usage of fwrite()
function in handling different data.
6/9/2021 3.2 _ Reading and Writing Functions in Files 60
61. 6/9/2021 3.2 _ Reading and Writing Functions in Files 61
The first fwrite( ) function writes only
the first three elements of the array
into the file. But, the second one
writes the last three elements of the
array into the file.
62. Example 7
• Write a C Program to Write the details about 3
students into the file sample.txt using fwrite()
function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 62
63. 6/9/2021 3.2 _ Reading and Writing Functions in Files 63
64. 6/9/2021 3.2 _ Reading and Writing Functions in Files 64
65. Practice Problem 1
• Get a line of text from the user and write it
into a file named „sample.txt‟. Read the
contents from the file and display it on the
monitor. Use fgetc() and fputc() functions to
manipulate the file.
6/9/2021 3.2 _ Reading and Writing Functions in Files 65
66. Practice Problem 2
• Write a program to copy the content of one
file into another one. Get the source and
target file names from the user.
6/9/2021 3.2 _ Reading and Writing Functions in Files 66
67. Practice Problem 3
• Write a C program to compare two files for
checking whether two files contains the same
content or not.
6/9/2021 3.2 _ Reading and Writing Functions in Files 67
68. Practice Problem 5
• Write a program to add some content at the
end to the existing file.
6/9/2021 3.2 _ Reading and Writing Functions in Files 68
69. Practice Problem 5
• Write a program to get the details (such as
Name, Roll No, five subjects marks ) of N
students and find the Total mark and Rank for
each student. Write Name, RollNo, Total mark
and Rank for each student into a file named
“studentdb.txt” using formatted file I/O
functions and also display these details in
tabular format.
6/9/2021 3.2 _ Reading and Writing Functions in Files 69
70. Practice Problem 6
• Write a program to create and manage a student
database with the listed operations
1. Add a new student by giving his/her roll number,
name and average mark.
2. Display the details about a student for a given roll
number
3. Display the details of all students in the database
4. Update the average mark of a student for a given roll
number
5. Delete a student record if roll number is given
6/9/2021 3.2 _ Reading and Writing Functions in Files 70
72. UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
73. Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 73
3.3 _ Manipulating, Removing and
Renaming a File
74. Sequential Access and Random Access Files
• Based on the method of accessing the data stored, files
can be classified into two types.
– Sequential access file
– Random access file
• In the sequential access file, data is kept in sequential
order. To access the last record of the file, we need to
read all records preceding to that record.
– Hence, it takes more time.
• But, in random access files data can be read and
modified at any random position. Unlike sequential
access, the any record can be read directly.
– Hence, it takes less time.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
74
75. Difference b/w Sequential and Random Access Files
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
75
76. Random Accessing in Files
• To achieve random accessing in files, the
following functions are used
– fseek()
– ftell()
– rewind()
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
76
77. Manipulating file position indicator using
fseek( ) function
• If there are many records inside a file and
need to access a record at a specific position
fseek( ) is used.
• As the name suggests, fseek() moves file
pointer associated with a given file to a
specific position.
• The fseek() function returns 0 if the move is
successful, else it returns a non-zero value.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
77
78. fseek() function
• fptr - It is the pointer to the file.
• Offset - It indicates the number of bytes to move from
the position specified by the third argument. The
positive value of offset makes the move in the forward
direction whereas the negative value in the
backward(reverse) direction.
• Position - It defines the point with respect to which the
file pointer needs to be moved. It has three values:
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
78
80. ftell( ) function
• The ftell() function is used to return the
position of file pointer in the file with respect
to starting of the file.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
80
81. Example
• The value of p is 12 which also indicate the
size of the file.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
81
82. rewind( ) function
• The rewind function sets the file position to
the beginning of the file.
• The rewind( ) is equivalent to
– fseek (fptr, 0, SEEK_SET).
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
82
83. Example
• Write a program to reverse the contents of
the text file using fseek() function.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
83
85. Removing a file : remove ( ) function
• The remove function can be used to delete a
file that is not opened already.
• The function returns zero if file is deleted
successfully, else returns a non-zero value.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
85
86. Renaming a file: rename ( ) function
• The function rename() is used to change the
name of the file
• i.e. from old_name to new_name without
changing the content present in the file.
• Syntax:
– If the file is renamed successfully, zero is returned.
– On failure, a nonzero value is returned.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
86
88. UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
89. Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 89
3.4 _ Command Line Arguments
90. Command-line Arguments
• Command line argument is a parameter
supplied to the program when it is invoked.
• It is possible to pass values from the
command line to the C programs when they
are executed.
• These values are called command line
arguments.
• Executable code of the program should be
compiled from DOS prompt.
6/9/2021 3.4 _ Command Line Arguments 90
91. Command-line Arguments
• The command line arguments are handled by
arguments given in main() function.
• The main() can be defined as,
6/9/2021 3.4 _ Command Line Arguments 91
92. Command-line Arguments
• The first argument argc refers to the number
of arguments passed to main().
• and the second argument argv[] is an array of
character pointers which points to each
argument passed to the main().
6/9/2021 3.4 _ Command Line Arguments 92
93. Command-line Arguments
• The array argv contains the elements
– argv[0] holds the name of the program itself.
– argv[1] is a pointer to the first command line argument
supplied
– argv[2] is a pointer to the second command line argument
supplied
– …….
– argv[argc-1] is a pointer to the last command line
argument supplied to the program.
• If no argument is supplied to the program, the
parameter argc will be set to one.
• if one argument is passed then argc is set to 2.
6/9/2021 3.4 _ Command Line Arguments 93
94. Command-line Arguments
• Steps to be followed to execute program using
Command Line Argument inside Borland C Compiler :
– Step 1 : Enter a Program and compile it.
– Step 2 : Open File menu inside Borland C.
– Step 3 : Click on DOS Shell.
– Step 4 : In the Command Prompt type the filename
(Program name without any extension) with the
arguments and press Enter Key using the format “filename
value 1 value 2 ..... Value m” . Program will be executed
with the given arguments and output is generated.
– Step 5 : Type “exit” command to return to Borland C
6/9/2021 3.4 _ Command Line Arguments 94
95. Example 1
• Write an example program to checks if there
is any argument supplied from the command
line and display these arguments.
6/9/2021 3.4 _ Command Line Arguments 95
105. UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
106. Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 106
3.5 _ Preprocessor
107. Preprocessor
• As the name suggests preprocessors are programs that
processes the source code before compilation as shown in
figure.
• Preprocessor provides preprocessor directives which tell
the compiler to preprocess the source code before the
complier starts its work.
• All the preprocessor directives begin with a “#” (hash)
symbol.
• The preprocessor directives can be placed anywhere in the
program.
6/9/2021 3.5 _ Preprocessor 107
108. Types of Preprocessor directives
• There are three different types of
preprocessor directives :
– Macros
– File Inclusion
– Conditional Compilation
6/9/2021 3.5 _ Preprocessor 108
109. Macros
• Macros are piece of code in a program which
is assigned with some name.
• Whenever this name is encountered by the
compiler the compiler replaces the name with
the actual piece of code.
• The “#define” directive is used to define a
macro.
• There are two types of macros –
– one which takes the argument and
– another which does not take any argument.
6/9/2021 3.5 _ Preprocessor 109
111. Macros without argument
• Every occurrences of macro name is replaced
with the actual piece of code by the compiler.
• This kind of macros usually used to give symbolic
names to numeric constants.
• There is no semi-colon(“;‟) is needed at the end
of a macro definition.
6/9/2021 3.5 _ Preprocessor 111
113. Macros with arguments
• It is also possible to pass arguments to
macros.
• Macro with arguments works similarly as
functions.
6/9/2021 3.5 _ Preprocessor 113
117. File Inclusion
• The #include preprocessor is used to include
header files to a C program.
• This directive instructs the compiler to include a
specified file to the C program.
• Here, "stdio.h" is a header file.
• The #include preprocessor directive replaces the
above line with the contents of stdio.h header
file which contain function and macro definitions.
6/9/2021 3.5 _ Preprocessor 117
118. File Inclusion
• Rules for file inclusion are:
– 1. File inclusive Directives are used to include
standard or user define header file inside C Program.
– 2. File inclusive directory checks included header file
inside same directory (if path is not mentioned).
– 3. File inclusive directives begins with #include
– 4. If Path is mentioned then it will include the header
file present in the location specified by that path.
– 5. Instead of using triangular brackets we use “Double
Quote” for inclusion of user defined header file.
6/9/2021 3.5 _ Preprocessor 118
121. Conditional Compilation
• Conditional compilation is the process of selecting
which code to compile and which code to not compile
similar to the #if / #else / #endif in C and C++.
• Conditional Compilation directives helps to include or
skip a specific block of code in the source code based
on some conditions.
• This can be done with the help of “ifdef” and “endif”
preprocessing directives.
• If the macro in #ifdef is defined, then the block of
statements will be executed normally. But, if it is not
defined, then the compiler will simply skip that block
of statements.
6/9/2021 3.5 _ Preprocessor 121