The document discusses file management in C programming. It defines a file as a sequence of bytes stored on disk for permanent storage of data. It describes basic file operations like opening, reading, writing and closing files. It explains functions for high level input/output like fopen(), fclose(), getc(), putc(), fprintf(), fscanf(), getw(), putw() and their usage. It also covers error handling functions like feof() and ferror(). The document discusses random access of files using functions like ftell(), fseek() and rewind(). It finally talks about command line arguments and how they are passed to main() in C programs.
File handling in C allows programs to perform operations on files stored on the local file system such as creation, opening, reading, writing and deletion of files. Common file handling functions include fopen() to open a file, fprintf() and fscanf() to write and read from files, fputc() and fgetc() to write and read single characters, and fclose() to close files. Binary files store data directly from memory to disk and allow for random access of records using functions like fseek(), ftell() and rewind(). Command line arguments can be accessed in the main() function through the argc and argv[] parameters.
This document discusses file handling in C programming. It describes the high level and low level methods of performing file operations in C using functions like fopen(), fclose(), getc(), putc(), fprintf(), fscanf(), getw(), putw(), fseek(), and ftell(). It explains how to open, read, write, close and perform random access on files. Functions like fopen(), fclose() are used to open and close files while getc(), putc(), fprintf(), fscanf() are used to read and write data from files.
Files allow data to be permanently stored and accessed by programs. Basic file operations include opening, reading, writing, and closing files. To open a file, its name and access mode are passed to the fopen function, which returns a file pointer used for subsequent read/write operations. Characters can be read from and written to files using functions like getc and putc. Command line arguments passed when a program launches are accessible through the argc and argv parameters of the main function.
The document discusses files in C programming and file input/output operations. It defines what a file is and explains the need for files when storing and accessing data. There are two main types of files - text files and binary files. The key file I/O functions in C like fopen(), fclose(), fprintf(), fscanf(), fgets(), fputs() and their usage are explained. Both formatted and unformatted I/O functions are covered along with reading and writing characters, integers and strings to files.
The document discusses file management in C. It defines a file as a collection of related data treated as a single unit by computers. C uses the FILE structure to store file attributes. The document outlines opening, reading, writing and closing files in C using functions like fopen(), fclose(), fread(), fwrite(), fseek(), ftell() and handling errors. It also discusses reading/writing characters using getc()/putc() and integers using getw()/putw() as well as formatted input/output with fscanf() and fprintf(). Random access to files using fseek() is also covered.
A file is a collection of related data that a computer treats as a single unit. Files allow data to be stored permanently even when the computer is shut down. C uses the FILE structure to store attributes of a file. Files allow for flexible data storage and retrieval of large data volumes like experimental results. Key file operations in C include opening, reading, writing, and closing files. Functions like fopen(), fread(), fwrite(), fclose() perform these operations.
This video has covered FILES chapter in Data Structure using C for BCA II semester, as per syllabus prescribed by Karnatak University , Dharwad,Karnataka,INDIA.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
This document provides an overview of various file handling functions in C, including FILE structure, fopen(), fclose(), file access modes, fputs(), fgets(), fputc(), fgetc(), fprintf(), fscanf(), fwrite(), fread(), freopen(), fflush(), feof(), fseek(), ftell(), fgetpos(), fsetpos(), rewind(), perror(), and examples of how to use each function. It explains concepts like FILE pointer, size_t and fpos_t data types used for file handling.
1) A file stores related data permanently on secondary storage like hard disks. It supports volatile main memory by storing data when the system shuts down.
2) A file name typically contains a primary name and optional extension separated by a period. File information like name and read/write position is stored in a file information table.
3) Standard input, output, and error streams (stdin, stdout, stderr) allow programs to read from and write to files and devices. Functions like fopen(), fclose(), fread(), fwrite() manage file access.
File handling in C programming uses file streams as the means of communication between programs and data files. The input stream extracts data from files and supplies it to the program, while the output stream stores data from the program into files. To handle file input/output, header file fstream.h is included, which contains ifstream and ofstream classes. Common file operations include opening, reading, writing, and closing files using functions like fopen(), fgetc(), fputs(), fclose(), and checking for end-of-file conditions. Files can be opened in different modes like read, write, append depending on the operation to be performed.
File Operation such as
Reading the file content
Writing the content to the file
Copying the content from one file to another file
Counting the number of character, words and lines of the file
The document discusses various C programming concepts like typedef, bitfields, enumeration, file I/O, text files vs binary files. typedef allows defining a new name for an already defined datatype. Bitfields allow packing structure members efficiently using bits. Enumeration defines a set of named integer constants. File I/O functions like fopen, fclose, fread, fwrite are used to read and write data to files. Text files contain human readable characters while binary files store data as bytes.
This document discusses file handling in C programming. It describes how to perform operations like creating, opening, reading, writing, and deleting files. It provides the functions used for each operation, such as fopen() to open a file, fprintf() to write to a file, and fclose() to close a file. It also discusses concepts like random access of files using fseek(), reading/writing single characters with fgetc()/fputc(), and handling binary files and command line arguments.
This document discusses file handling in C. It covers opening, reading from, writing to, and closing files. The key points are:
- Files allow storing data permanently that can be accessed by programs. Common file operations in C include opening, reading, writing, and closing files.
- To open a file, the fopen function is used, specifying the file name and mode (e.g. read, write, append). This returns a FILE pointer used for subsequent operations.
- Common functions for reading from files include getc, fgetc, fscanf. Common functions for writing include putc, fputc, fprintf.
- It is important to close files after
1. A file represents a sequence of bytes that can store data even if a program terminates. There are two types of files: text files containing plain text and binary files containing data in binary form (0s and 1s).
2. Common file operations include opening, closing, reading, and writing files. Functions like fopen(), fclose(), fgetc(), fputc(), fread(), and fwrite() are used to perform these operations.
3. Files allow permanent storage of data that can be accessed and transferred between computers. Programs demonstrate how to perform tasks like reading a file, copying file contents, finding the largest number in a file, and appending data to an existing file.
This document discusses file input/output (I/O) operations in C programming. It covers opening, closing, reading from and writing to files. Specific file I/O functions covered include fopen(), fclose(), getc(), putc(), getw(), putw(), fprintf(), fscanf(), feof(), ferror(), fseek(), ftell(), and rewind(). Error handling during file I/O and random access to files using functions like fseek() are also discussed. Examples are provided to demonstrate reading integer and mixed data types from files and writing data to files.
File handling in C allows programs to read from and write to files. A file contains related data treated as a single unit that is stored in secondary storage. C uses the FILE structure to represent an opened file and track attributes. The basic file operations are opening a file with fopen, reading/writing with fread/fwrite, seeking position with fseek, getting position with ftell, and closing with fclose. Files can be opened in different modes like read, write, append to specify how the file will be used.
File handling in C allows programs to permanently store and retrieve large amounts of data from files. Files must be opened before use and closed after to ensure data is properly written. Basic file operations include opening, reading, writing, and closing files. Functions like fopen open a file and return a file pointer. fread and fwrite can read and write arrays of data. An example shows merging two text files containing numbers into a single output file by comparing the numbers and writing the smaller value.
This document discusses file operations in C including opening, reading, writing, and closing files. It describes different file types and functions used for file input/output like fopen(), fclose(), fread(), fwrite(), getc(), putc(), fseek(), ftell(), and more. It also covers command line arguments, random access of files using functions like fseek() and ftell(), and file system functions such as rename(), remove(), and chmod().
This document discusses data files in C programming. It covers opening and closing data files, creating data files, and processing data files. Some key points:
1) To access a data file in C, it must first be opened using the fopen() function, which returns a FILE pointer. This pointer is then used to read from or write to the file.
2) A data file can be created by writing data from a program to a new file using functions like putc() and fputs().
3) To process a data file, functions like fgetc() and fputs() can be used to read and write data, character by character or as strings. Command line arguments passed to
File management functions in C allow programs to work with files. They provide functions to open, read, write, and close files. Some key functions include fopen() to open a file, fread() and fwrite() to read from and write to files, and fclose() to close a file. Files can be opened in different modes like read, write, append depending on whether the file needs to be read from or written to. Command line arguments allow passing of inputs to a program from the command line when it is launched.
APM event hosted by the Midlands Network on 30 April 2025.
Speaker: Sacha Hind, Senior Programme Manager, Network Rail
With fierce competition in today’s job market, candidates need a lot more than a good CV and interview skills to stand out from the crowd.
Based on her own experience of progressing to a senior project role and leading a team of 35 project professionals, Sacha shared not just how to land that dream role, but how to be successful in it and most importantly, how to enjoy it!
Sacha included her top tips for aspiring leaders – the things you really need to know but people rarely tell you!
We also celebrated our Midlands Regional Network Awards 2025, and presenting the award for Midlands Student of the Year 2025.
This session provided the opportunity for personal reflection on areas attendees are currently focussing on in order to be successful versus what really makes a difference.
Sacha answered some common questions about what it takes to thrive at a senior level in a fast-paced project environment: Do I need a degree? How do I balance work with family and life outside of work? How do I get leadership experience before I become a line manager?
The session was full of practical takeaways and the audience also had the opportunity to get their questions answered on the evening with a live Q&A session.
Attendees hopefully came away feeling more confident, motivated and empowered to progress their careers
Ad
More Related Content
Similar to want to learn files,then just use this ppt to learn (20)
This video has covered FILES chapter in Data Structure using C for BCA II semester, as per syllabus prescribed by Karnatak University , Dharwad,Karnataka,INDIA.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
This document provides an overview of various file handling functions in C, including FILE structure, fopen(), fclose(), file access modes, fputs(), fgets(), fputc(), fgetc(), fprintf(), fscanf(), fwrite(), fread(), freopen(), fflush(), feof(), fseek(), ftell(), fgetpos(), fsetpos(), rewind(), perror(), and examples of how to use each function. It explains concepts like FILE pointer, size_t and fpos_t data types used for file handling.
1) A file stores related data permanently on secondary storage like hard disks. It supports volatile main memory by storing data when the system shuts down.
2) A file name typically contains a primary name and optional extension separated by a period. File information like name and read/write position is stored in a file information table.
3) Standard input, output, and error streams (stdin, stdout, stderr) allow programs to read from and write to files and devices. Functions like fopen(), fclose(), fread(), fwrite() manage file access.
File handling in C programming uses file streams as the means of communication between programs and data files. The input stream extracts data from files and supplies it to the program, while the output stream stores data from the program into files. To handle file input/output, header file fstream.h is included, which contains ifstream and ofstream classes. Common file operations include opening, reading, writing, and closing files using functions like fopen(), fgetc(), fputs(), fclose(), and checking for end-of-file conditions. Files can be opened in different modes like read, write, append depending on the operation to be performed.
File Operation such as
Reading the file content
Writing the content to the file
Copying the content from one file to another file
Counting the number of character, words and lines of the file
The document discusses various C programming concepts like typedef, bitfields, enumeration, file I/O, text files vs binary files. typedef allows defining a new name for an already defined datatype. Bitfields allow packing structure members efficiently using bits. Enumeration defines a set of named integer constants. File I/O functions like fopen, fclose, fread, fwrite are used to read and write data to files. Text files contain human readable characters while binary files store data as bytes.
This document discusses file handling in C programming. It describes how to perform operations like creating, opening, reading, writing, and deleting files. It provides the functions used for each operation, such as fopen() to open a file, fprintf() to write to a file, and fclose() to close a file. It also discusses concepts like random access of files using fseek(), reading/writing single characters with fgetc()/fputc(), and handling binary files and command line arguments.
This document discusses file handling in C. It covers opening, reading from, writing to, and closing files. The key points are:
- Files allow storing data permanently that can be accessed by programs. Common file operations in C include opening, reading, writing, and closing files.
- To open a file, the fopen function is used, specifying the file name and mode (e.g. read, write, append). This returns a FILE pointer used for subsequent operations.
- Common functions for reading from files include getc, fgetc, fscanf. Common functions for writing include putc, fputc, fprintf.
- It is important to close files after
1. A file represents a sequence of bytes that can store data even if a program terminates. There are two types of files: text files containing plain text and binary files containing data in binary form (0s and 1s).
2. Common file operations include opening, closing, reading, and writing files. Functions like fopen(), fclose(), fgetc(), fputc(), fread(), and fwrite() are used to perform these operations.
3. Files allow permanent storage of data that can be accessed and transferred between computers. Programs demonstrate how to perform tasks like reading a file, copying file contents, finding the largest number in a file, and appending data to an existing file.
This document discusses file input/output (I/O) operations in C programming. It covers opening, closing, reading from and writing to files. Specific file I/O functions covered include fopen(), fclose(), getc(), putc(), getw(), putw(), fprintf(), fscanf(), feof(), ferror(), fseek(), ftell(), and rewind(). Error handling during file I/O and random access to files using functions like fseek() are also discussed. Examples are provided to demonstrate reading integer and mixed data types from files and writing data to files.
File handling in C allows programs to read from and write to files. A file contains related data treated as a single unit that is stored in secondary storage. C uses the FILE structure to represent an opened file and track attributes. The basic file operations are opening a file with fopen, reading/writing with fread/fwrite, seeking position with fseek, getting position with ftell, and closing with fclose. Files can be opened in different modes like read, write, append to specify how the file will be used.
File handling in C allows programs to permanently store and retrieve large amounts of data from files. Files must be opened before use and closed after to ensure data is properly written. Basic file operations include opening, reading, writing, and closing files. Functions like fopen open a file and return a file pointer. fread and fwrite can read and write arrays of data. An example shows merging two text files containing numbers into a single output file by comparing the numbers and writing the smaller value.
This document discusses file operations in C including opening, reading, writing, and closing files. It describes different file types and functions used for file input/output like fopen(), fclose(), fread(), fwrite(), getc(), putc(), fseek(), ftell(), and more. It also covers command line arguments, random access of files using functions like fseek() and ftell(), and file system functions such as rename(), remove(), and chmod().
This document discusses data files in C programming. It covers opening and closing data files, creating data files, and processing data files. Some key points:
1) To access a data file in C, it must first be opened using the fopen() function, which returns a FILE pointer. This pointer is then used to read from or write to the file.
2) A data file can be created by writing data from a program to a new file using functions like putc() and fputs().
3) To process a data file, functions like fgetc() and fputs() can be used to read and write data, character by character or as strings. Command line arguments passed to
File management functions in C allow programs to work with files. They provide functions to open, read, write, and close files. Some key functions include fopen() to open a file, fread() and fwrite() to read from and write to files, and fclose() to close a file. Files can be opened in different modes like read, write, append depending on whether the file needs to be read from or written to. Command line arguments allow passing of inputs to a program from the command line when it is launched.
APM event hosted by the Midlands Network on 30 April 2025.
Speaker: Sacha Hind, Senior Programme Manager, Network Rail
With fierce competition in today’s job market, candidates need a lot more than a good CV and interview skills to stand out from the crowd.
Based on her own experience of progressing to a senior project role and leading a team of 35 project professionals, Sacha shared not just how to land that dream role, but how to be successful in it and most importantly, how to enjoy it!
Sacha included her top tips for aspiring leaders – the things you really need to know but people rarely tell you!
We also celebrated our Midlands Regional Network Awards 2025, and presenting the award for Midlands Student of the Year 2025.
This session provided the opportunity for personal reflection on areas attendees are currently focussing on in order to be successful versus what really makes a difference.
Sacha answered some common questions about what it takes to thrive at a senior level in a fast-paced project environment: Do I need a degree? How do I balance work with family and life outside of work? How do I get leadership experience before I become a line manager?
The session was full of practical takeaways and the audience also had the opportunity to get their questions answered on the evening with a live Q&A session.
Attendees hopefully came away feeling more confident, motivated and empowered to progress their careers
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
What makes space feel generous, and how architecture address this generosity in terms of atmosphere, metrics, and the implications of its scale? This edition of #Untagged explores these and other questions in its presentation of the 2024 edition of the Master in Collective Housing. The Master of Architecture in Collective Housing, MCH, is a postgraduate full-time international professional program of advanced architecture design in collective housing presented by Universidad Politécnica of Madrid (UPM) and Swiss Federal Institute of Technology (ETH).
Yearbook MCH 2024. Master in Advanced Studies in Collective Housing UPM - ETH
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...larencebapu132
This is short and accurate description of World war-1 (1914-18)
It can give you the perfect factual conceptual clarity on the great war
Regards Simanchala Sarab
Student of BABed(ITEP, Secondary stage)in History at Guru Nanak Dev University Amritsar Punjab 🙏🙏
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
How to Manage Opening & Closing Controls in Odoo 17 POSCeline George
In Odoo 17 Point of Sale, the opening and closing controls are key for cash management. At the start of a shift, cashiers log in and enter the starting cash amount, marking the beginning of financial tracking. Throughout the shift, every transaction is recorded, creating an audit trail.
Contact Lens:::: An Overview.pptx.: OptometryMushahidRaza8
A comprehensive guide for Optometry students: understanding in easy launguage of contact lens.
Don't forget to like,share and comments if you found it useful!.
Link your Lead Opportunities into Spreadsheet using odoo CRMCeline George
In Odoo 17 CRM, linking leads and opportunities to a spreadsheet can be done by exporting data or using Odoo’s built-in spreadsheet integration. To export, navigate to the CRM app, filter and select the relevant records, and then export the data in formats like CSV or XLSX, which can be opened in external spreadsheet tools such as Excel or Google Sheets.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...Celine George
Analytic accounts are used to track and manage financial transactions related to specific projects, departments, or business units. They provide detailed insights into costs and revenues at a granular level, independent of the main accounting system. This helps to better understand profitability, performance, and resource allocation, making it easier to make informed financial decisions and strategic planning.
The Pala kings were people-protectors. In fact, Gopal was elected to the throne only to end Matsya Nyaya. Bhagalpur Abhiledh states that Dharmapala imposed only fair taxes on the people. Rampala abolished the unjust taxes imposed by Bhima. The Pala rulers were lovers of learning. Vikramshila University was established by Dharmapala. He opened 50 other learning centers. A famous Buddhist scholar named Haribhadra was to be present in his court. Devpala appointed another Buddhist scholar named Veerdeva as the vice president of Nalanda Vihar. Among other scholars of this period, Sandhyakar Nandi, Chakrapani Dutta and Vajradatta are especially famous. Sandhyakar Nandi wrote the famous poem of this period 'Ramcharit'.
2. Introduction to Files
So far, the operations using C program are done on a prompt / terminal
which is not stored anywhere. But in the software industry, most of the
programs are written to store the information fetched from the program.
One such way is to store the fetched information in a file. Different
operations that can be performed on a file are:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Move the pointer to a specific location in a file
6. Closing a file
3. What is a File?
• A file can be treated as external storage. It consists of a sequence of bytes
residing on the disk.
• A program can create, read, and write into a file. Unlike an array, the data
in the file is retained even after the program finishes its execution. It's a
permanent storage medium.
• File handling in C programming uses FILE STREAM as a means of
communication between programs and data files.
• The INPUT STREAM extracts the data from the files and supplies it to the
program.
• The OUTPUT STREAM stores the data into the file supplied by the program.
• C uses a structure called FILE (defined in stdio.h) to store the attributes of a
file.
4. Declaring a File Pointer
• In C language, in order to declare a file, we use a file pointer. A file
pointer is a pointer variable that specifies the next byte to be read or
written to.
• Every time a file is opened, the file pointer points to the beginning of
the file. A file is declared as follows:
• FILE *fp;
• //fp is the name of the file pointer
5. The basic File operations
Open a file
Read data from a file
Write data into a file
Close a file
6. Library Functions for FILE handling
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
7. Opening File: fopen()
• The fopen() function is used to open a file. The syntax of the fopen() is
given below.
• fp = FILE *fopen(const char *filename, const char *mode);
• fp is the file pointer that holds the reference to the file, the filename is
the name of the file to be opened or created, and mode specifies the
purpose of opening a file such as for reading or writing.
• FILE is an object type used for storing information about the file
stream.
8. Opening File: fopen()
• A file can be opened in
different modes. Below
are some of the most
commonly used modes for
opening or creating a file.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
10. • A file needs to be closed after a read or write operation to release the
memory allocated by the program.
• In C, a file is closed using the fclose() function.
• This returns 0 on success and EOF in the case of a failure.
• An EOF is defined in the library called stdio.h.
• EOF is a constant defined as a negative integer value which denotes
that the end of the file has reached.
Syntax: fclose( FILE *fp );
Closing File: fclose()
11. Writing and Reading Functions
1. getc(): Read a single character from the opened file
2. putc(): Write a single character from the opened file
3. fgetc(): Reads a character from the file with the help of the file pointer fp. It returns EOF at
the end of the file
4. fputc(): Writes a character into the file with the help of the file pointer fp. It returns EOF in
the case of an error
5. fgets(): Read a line of message from the file.
6. fputs(): Write’s a line of message into the file.
7. fprintf(): It sends formatted output to a stream.
8. fscanf(): It reads formatted data from the stream.
9. putw(): Write’s an integer data into a file.
10.getw(): Read integer data from the file.
12. getc(): Read a single character
getc():
This function reads a single character from the opened file and moves
the file pointer. It returns EOF if end of file reached.
Syntax: char ch=getc(fp);
It is available in conio.h
14. putc(): Write a single character
putc():
This function is used to write a single character into a file. If an error
occurs it returns EOF.
Syntax: putc( ch, Fp );
‘Fp’ indicates File pointer.
16. fputc(): Write a single character
fputc():
This function writes a character c into the file with the help of the file
pointer fp. It returns EOF in the case of an error.
Syntax: int fputc( int c, FILE *fp );
18. fgetc(): Read a single character
fgetc():
The fgetc() function returns a single character from the file. It gets a
character from the stream. It returns EOF at the end of file.
Syntax: int fgetc(FILE *fp)
20. fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read
string from stream
fputs():
The fputs() function writes a line of characters into file. It outputs string
to a stream.
Syntax: int fputs( const char *s, FILE *fp );
This function writes string s to the file with the help of the reference
pointer fp.
22. fputs() and fgets()
fgets():
The fgets() function reads a line of characters from file. It gets string
from a stream.
Syntax: char *fgets( char *buffer, int n, FILE *fp );
fgets() reads up to n characters from the input stream referenced by fp.
The string reads and copied into the character buffer and terminates
when a null character is encountered.
24. fprintf() and fscanf()
fprintf():
The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
Syntax: int fprintf(FILE *fp, const char *format)
26. fprintf() and fscanf()
fscanf():
The fscanf() function is used to read set of characters from file. It reads
a word from the file and returns EOF at the end of file.
Syntax: int fscanf(FILE *fp, const char *format , ..)
29. #include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");
if (fptr == NULL)
{
printf("File does not exists n");
return 0;
}
Hold employee information in to a File
printf("Enter the idn");
scanf("%d", &id);
fprintf(fptr, "Id= %dn", id);
printf("Enter the name n");
scanf("%s", name);
fprintf(fptr, "Name= %sn", name);
printf("Enter the salaryn");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2fn", salary);
fclose(fptr);
}
30. getw() and putw()
putw():
This function is used to write an integer value to file. This function
deals with integer data only.
Syntax: putw( int v, FILE *FP);
getw():
This function returns the integer value from a file and increments the
file pointer. This function deals with only integers.
Syntax: int getw( FILE *FP );
31. Block Input and Output
• It is important to know how numerical data is stored on the disk by fprintf() function.
• Text and characters requires one byte for storing them with fprintf(). Similarly for storing
numbers in memory two bytes and for floats four bytes.
• For example 3456 occupies two bytes in memory. But when it is transferred to the disk
file using fprint() function it would occupies four bytes. For each character it
requires one byte. Even for float also each digit including dot(.) requires one byte.
• Thus large amount of integers and float data requires large space on the disk. To
overcome this problem files should be read and write in binary mode, for which we use
fread() and fwrite() functions.
• fwrite(): This function is used for writing an entire structure block to a given file.
• fread(): This function is used for reading an entire block from a given file.
34. for(i=0; i<j ; i++ )
{
fread(&s1, sizeof(s1), 1, fp);
printf(“Name %s t Age %d n”, s1[i].name, s1[i].age);
}
}//else close
fclose(fp);
}//main close
Block Input and Output
35. fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into
file at desired location.
Syntax: int fseek(FILE *stream, long int offset, int position)
Three are arguments are to be passed through this function. They are:
1. File pointer
2. Offset: offset may be positive (moving in forward from current position) or negative (moving
backwards). The offset being a variable of type long.
3. The current position of file pointer.
• There are 3 constants used in the fseek() function for position: SEEK_SET, SEEK_CUR and
SEEK_END
Integer
value
Constant Location in the File
0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position of the file pointer
2 SEEK_END End of the file
36. #include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is a C program", fp);
fseek( fp, 7, SEEK_SET );
fputs("File handling in C", fp);
fclose(fp);
}
fseek() Example
myfile.txt
This is File handling in C
37. rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It
is useful if you have to use stream many times.
Syntax: void rewind(FILE *stream)
Example:
File: file.txt
this is a simple text
38. File Name: rewind.c
#include<stdio.h>
void main(){
FILE *fp;
char c;
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}
rewind() Example
File: file.txt
this is a simple text
Output:
this is a simple textthis is a simple text
39. ftell() function
• The ftell() function returns the current file position of the specified stream.
• We can use ftell() function to get the total size of a file after moving file
pointer at the end of file.
• We can use SEEK_END constant to move the file pointer at the end of file.
Syntax: long int ftell(FILE *stream)
40. File Name: ftell.c
#include <stdio.h>
void main (){
FILE *fp;
int length;
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
}
ftell() Example
File: file.txt
this is a simple text
Output:
Size of file: 21 bytes