SlideShare a Scribd company logo
Programming C
File Handling in C
File
Handling
• File handling is the process in which we create,
open, read, write, and close operations on a
file.
• Programs are written to store and retrieve the
information from file.
• The data stored in the file can be accessed,
updated, and deleted anywhere and anytime
providing high reusability.
• Portable - Without losing any data, files can
be transferred to another in the computer
system
• Storage - Files allow you to store a large
amount of data and easily access whole or
part of files.
Types of
Files - TEXT
A text file contains data in the form of
ASCII characters and is generally used
to store a stream of characters.
 Each line in a text file ends with a new
line character (‘n’).
 It can be read or written by any text
editor.
 They are generally stored with .txt file
extension.
 Text files can also be used to store the
source code.
Types of Files
- BINARY
A binary file contains data
in binary form (i.e. 0’s and
1’s) instead of ASCII characters.
 The binary files can be created
only from within a program and
their contents can only be
read by a program.
 More secure as they are not
easily readable.
 They are generally stored
with .bin file extension.
File
Operations
• fopen() – To open existing file or create
new file with attributes likes “a” or “a+”
or “w” or “w+”.
• fopen() – To open existing file for
reading with attributes likes “r” or “r+”
• fscanf() or fgets() – To read data from
opened file.
• fprintf() or fputs() – To write data to
opened file.
• fseek(), rewind() – To move
(cursor/pointer) to specific location in a
file.
• fclose() – To close the opened file.
Opening a
file
•FILE* pointername;
•FILE* fopen(const chat
*filename,
• const chat
*accessmode )
• Filename – Name of the file
present in the same directory
as the source program or full
path.
• Accessmode – Indicates the
operations (read, write etc.) for
which file to be opened.
• Returns file pointer if file is
opened successfully, if not
NULL.
•#include <stdlib.h>
•int main()
•{
• FILE* fptr;
• fptr =
fopen("filename.txt", "r");
• if (fptr == NULL) {
• printf("The file is not
opened");
• exit(0);
• }
• return 0;
•}
File Modes - TEXT
Opening
Modes
Description
r
If the file is found and opened successfully, fopen( ) loads it into memory and sets up a
pointer that points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.
w
Open for writing in text mode. If the file exists, its contents are overwritten. If the file
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
a
If the file is found and opened successfully, fopen( ) loads it into memory and sets up a
pointer that points to the last character in it. It opens only in the append mode. If the file
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
File Modes – TEXT
Opening
Modes
Description
r+
If the file is found and opened successfully, fopen( ) loads it into memory and sets
up a pointer that points to the first character in it. Returns NULL, if unable to open
the file.
w+
If the file exists, its contents are overwritten. If the file doesn’t exist a new file is
created. Returns NULL, if unable to open the file.
a+
If the file is found and opened successfully, fopen( ) loads it into memory and sets
up a pointer that points to the last character in it. It opens the file in both reading
and append mode. If the file doesn’t exist, a new file is created. Returns NULL, if
unable to open the file.
File Modes - BINARY
Opening
Modes
Description
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
wb
Open for writing in binary mode. If the file exists, its contents are overwritten. If
the file does not exist, it will be created.
ab
Open for append in binary mode. Data is added to the end of the file. If the file
does not exist, it will be created.
rb+
Open for both reading and writing in binary mode. If the file does not exist, fopen(
) returns NULL.
wb+
Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
ab+
Open for both reading and appending in binary mode. If the file does not exist, it
will be created.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w");
if (fptr == NULL) {
printf("The file is not opened. The program will “);
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}
Creating a file
The file read operation in C can
be performed using functions
fscanf() or fgets().
Similar to scanf and gets
functions, but fscanf and fgets
have file pointer as parameter.
There are also other functions
we can use to read from a file
Reading from file
fscanf()- Use formatted string and variable
arguments list to take input from a file.
fgets() - Input the whole line from the file.
fgetc() - Reads a single character from the file.
fgetw() - Reads a number from a file.
fread() - Reads the specified amount of bytes
to the binary file.
All file reading functions return
EOF (End Of File) when they
reach the end of the file while
reading.
After reading a particular part
of the file, the file pointer will
be automatically moved to the
end of the last read
character.
Reading from file
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3,
&year);
char c = fgetc(fptr);
#include <stdio.h>
#include <string.h>
int main()
{
FILE* filePointer;
char dataToBeRead[50];
filePointer = fopen("Hi.txt", "r");
if (filePointer == NULL) {
printf("Hi.txt file failed to open.");
}
else {
printf("The file is now opened.n");
Reading from TEXT file
while (fgets(dataToBeRead, 50, filePointer)
!= NULL) {
printf("%sn", dataToBeRead);
} //while loop ending
fclose(filePointer);
printf("nData read successfully and file is now closed.");
} //else body ending
return 0;
} //main body ending.
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("D:program.bin", "rb")) == NULL) {
printf("Error! opening file");
exit(1);
}
Reading from BINARY file
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum), 1,
fptr);
printf("n1: %dtn2: %dtn3: %dn", num.n1,
num.n2,
num.n3);
}
fclose(fptr);
return 0;
}
The file write operations can
be performed by the functions
fprintf() and fputs() with
similarities to read operations.
Writing to a file
fprintf() - Use formatted string and variable
arguments list to print output to the file.
fputs() – Prints the whole line in the file and
new line at the end.
fputc() – Prints a single character into the file.
fputw() – Prints a number to the file.
fwrite() – Writes the specified bytes of data
from a binary file.
#include <stdio.h>
#include <string.h>
int main()
{
FILE* filePointer;
char dataToBeWritten[50] = "Hi welcome to C
progrmming n File Handling nConcepts";
filePointer = fopen("Hi.txt", "w");
//filePointer = fopen("D:Hi.c", "w");
if (filePointer == NULL) {
printf("H.c file failed to open.");
}
Writing to TEXT file
else {
if (strlen(dataToBeWritten) > 0) {
fputs(dataToBeWritten, filePointer);
fputs("n", filePointer);
}
fclose(filePointer);
printf("Data written and file is now closed.");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("D:program.bin", "wb")) ==
NULL) {
printf("Error! opening file");
exit(1);
}
Writing to BINARY file
int flag = 0;
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
flag = fwrite(&num, sizeof(struct threeNum), 1,
fptr);
}
if (!flag) {
printf("Write Operation Failure");
}
else {
printf("Write Operation Successful");
} // fclose(fptr); return 0; }
The fclose() function is
used to close the file.
After successful file
operations, close a file to
remove it from the
memory.
Closing a file
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
//perform some operations.
fclose(fptr);
 If file has multiple records and we need to access a particular
record (at a specific position), use fseek() which provides an
easier way to get to the required data.
We use fseek() Instead of looping through all the records before
it to get the record which consumes more memory and
operational time.
fseek() helps to reduce memory consumption and operational
time.
fseek() function in C seeks the cursor to the given record in the
file.
int fseek(FILE *fptr, long int offset, int pos)
Other File Operations - fseek()
 Its used to bring the file
pointer to the beginning of
the file.
It can be used in place of
fseek() when you want the
file pointer at the start or
beginning of the file (BOF).
rewind (file_pointer);
Other File Operations - rewind()
#include <stdio.h>
int main()
{
FILE* fptr;
fptr = fopen("file.txt", "w+");
fprintf(fptr, “Welcome to C Programmingn");
rewind(fptr);
char buf[50];
fscanf(fptr, "%[^n]s", buf);
printf("%s", buf);
return 0;
}
 Its used to find out the
position of the file pointer
in the file with respect to
starting of the file.
long ftell (file_pointer);
Other File Operations - ftell()
#include <stdio.h>
int main()
{
FILE* fp = fopen(“file.txt", "r");
char string[20];
fscanf(fp, "%s", string);
printf("%ld", ftell(fp));
return 0;
}
• Create Student structure
(id,name,mark1,mark2,mark3,total,avg), read Student
details from the user except total and average, calculate the
total & average and write the student structure to file.
• Read the student file in the structure and display each
student details line by line.
• Write program to merge two input files data in to third file
and display the third file content.
Exercises
• The arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
• To support command line argument, programmer needs to change
the structure of main() function as
int main(int argc, char *argv[] )
• Here, argc counts the number of arguments. It counts the file name as
the first argument.
• The argv[] contains the total arguments. The first argument is the file
name always.
Command Line Arguments
#include<stdio.h>
void main(int argc, char *argv[] )
{
printf("Program name is: %sn", argv[0]);
if(argc < 2)
{
printf("No argument passed through command line.n");
}
else
{
printf("First argument is: %sn", argv[1]);
}
}
Example
#include<stdio.h>
#include<stdlib.h>
void main(int argc, char *argv[] )
{
if(argc >= 2)
{
int i=1,sum=0;
while(i <= argc)
{
sum+=atol(argv[i]); //atol Is the function from stdlib.h to convert str to int.
i++;
}
printf("Sum of commandline Arguments are : %dn", sum);
}
}
Example – Sum of digits using CLI
• https://www.javatpoint.com/c-programming-language-
tutorial
• https://www.tutorialspoint.com/cprogramming/index.htm
• https://www.programiz.com/c-programming
References
What Questions do you have
27
Thank you
Thank you
Ad

Recommended

File handing in C
File handing in C
shrishcg
 
PPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
file_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
sahakrishnan
 
File accessing modes in c
File accessing modes in c
manojmanoj218596
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
C-Programming File-handling-C.pptx
C-Programming File-handling-C.pptx
SKUP1
 
C-Programming File-handling-C.pptx
C-Programming File-handling-C.pptx
LECO9
 
File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1
Priyadarshini803769
 
Module 5 file cp
Module 5 file cp
Amarjith C K
 
Concept of file handling in c
Concept of file handling in c
MugdhaSharma11
 
File handling-c
File handling-c
CGC Technical campus,Mohali
 
File Handling in C Programming
File Handling in C Programming
Bosco Technical Training Society, Don Bosco Technical School (Aff. GGSIP University, New Delhi)
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
How to do file-handling - in C language
How to do file-handling - in C language
SwatiAtulJoshi
 
File in C language
File in C language
Manash Kumar Mondal
 
File handling With Solve Programs
File handling With Solve Programs
Rohan Gajre
 
PPS-II UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
VenkataRangaRaoKommi1
 
File Handling in C Programming for Beginners
File Handling in C Programming for Beginners
VSKAMCSPSGCT
 
file handling, dynamic memory allocation
file handling, dynamic memory allocation
indra Kishor
 
Module 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
Presentation of file handling in C language
Presentation of file handling in C language
Shruthi48
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
ssuserad38541
 
Lecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Topic - File operation.pptx
Topic - File operation.pptx
Adnan al-emran
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 

More Related Content

Similar to Programming C- File Handling , File Operation (20)

C-Programming File-handling-C.pptx
C-Programming File-handling-C.pptx
LECO9
 
File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1
Priyadarshini803769
 
Module 5 file cp
Module 5 file cp
Amarjith C K
 
Concept of file handling in c
Concept of file handling in c
MugdhaSharma11
 
File handling-c
File handling-c
CGC Technical campus,Mohali
 
File Handling in C Programming
File Handling in C Programming
Bosco Technical Training Society, Don Bosco Technical School (Aff. GGSIP University, New Delhi)
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
How to do file-handling - in C language
How to do file-handling - in C language
SwatiAtulJoshi
 
File in C language
File in C language
Manash Kumar Mondal
 
File handling With Solve Programs
File handling With Solve Programs
Rohan Gajre
 
PPS-II UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
VenkataRangaRaoKommi1
 
File Handling in C Programming for Beginners
File Handling in C Programming for Beginners
VSKAMCSPSGCT
 
file handling, dynamic memory allocation
file handling, dynamic memory allocation
indra Kishor
 
Module 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
Presentation of file handling in C language
Presentation of file handling in C language
Shruthi48
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
ssuserad38541
 
Lecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
Topic - File operation.pptx
Topic - File operation.pptx
Adnan al-emran
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
C-Programming File-handling-C.pptx
C-Programming File-handling-C.pptx
LECO9
 
File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1
Priyadarshini803769
 
Concept of file handling in c
Concept of file handling in c
MugdhaSharma11
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
How to do file-handling - in C language
How to do file-handling - in C language
SwatiAtulJoshi
 
File handling With Solve Programs
File handling With Solve Programs
Rohan Gajre
 
File Handling in C Programming for Beginners
File Handling in C Programming for Beginners
VSKAMCSPSGCT
 
file handling, dynamic memory allocation
file handling, dynamic memory allocation
indra Kishor
 
Module 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
Presentation of file handling in C language
Presentation of file handling in C language
Shruthi48
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
ssuserad38541
 
Topic - File operation.pptx
Topic - File operation.pptx
Adnan al-emran
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 

Recently uploaded (20)

NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
2025 Completing the Pre-SET Plan Form.pptx
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
How to Add New Item in CogMenu in Odoo 18
How to Add New Item in CogMenu in Odoo 18
Celine George
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
Code Profiling in Odoo 18 - Odoo 18 Slides
Code Profiling in Odoo 18 - Odoo 18 Slides
Celine George
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
2025 Completing the Pre-SET Plan Form.pptx
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
How to Add New Item in CogMenu in Odoo 18
How to Add New Item in CogMenu in Odoo 18
Celine George
 
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
 
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
CRYPTO TRADING COURSE BY FINANCEWORLD.IO
AndrewBorisenko3
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
Ad

Programming C- File Handling , File Operation

  • 2. File Handling • File handling is the process in which we create, open, read, write, and close operations on a file. • Programs are written to store and retrieve the information from file. • The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high reusability. • Portable - Without losing any data, files can be transferred to another in the computer system • Storage - Files allow you to store a large amount of data and easily access whole or part of files.
  • 3. Types of Files - TEXT A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.  Each line in a text file ends with a new line character (‘n’).  It can be read or written by any text editor.  They are generally stored with .txt file extension.  Text files can also be used to store the source code.
  • 4. Types of Files - BINARY A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.  The binary files can be created only from within a program and their contents can only be read by a program.  More secure as they are not easily readable.  They are generally stored with .bin file extension.
  • 5. File Operations • fopen() – To open existing file or create new file with attributes likes “a” or “a+” or “w” or “w+”. • fopen() – To open existing file for reading with attributes likes “r” or “r+” • fscanf() or fgets() – To read data from opened file. • fprintf() or fputs() – To write data to opened file. • fseek(), rewind() – To move (cursor/pointer) to specific location in a file. • fclose() – To close the opened file.
  • 6. Opening a file •FILE* pointername; •FILE* fopen(const chat *filename, • const chat *accessmode ) • Filename – Name of the file present in the same directory as the source program or full path. • Accessmode – Indicates the operations (read, write etc.) for which file to be opened. • Returns file pointer if file is opened successfully, if not NULL. •#include <stdlib.h> •int main() •{ • FILE* fptr; • fptr = fopen("filename.txt", "r"); • if (fptr == NULL) { • printf("The file is not opened"); • exit(0); • } • return 0; •}
  • 7. File Modes - TEXT Opening Modes Description r If the file is found and opened successfully, fopen( ) loads it into memory and sets up a pointer that points to the first character in it. If the file cannot be opened fopen( ) returns NULL. w Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. a If the file is found and opened successfully, fopen( ) loads it into memory and sets up a pointer that points to the last character in it. It opens only in the append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
  • 8. File Modes – TEXT Opening Modes Description r+ If the file is found and opened successfully, fopen( ) loads it into memory and sets up a pointer that points to the first character in it. Returns NULL, if unable to open the file. w+ If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open the file. a+ If the file is found and opened successfully, fopen( ) loads it into memory and sets up a pointer that points to the last character in it. It opens the file in both reading and append mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
  • 9. File Modes - BINARY Opening Modes Description rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL. wb Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. ab Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created. rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL. wb+ Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created. ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
  • 10. #include <stdio.h> #include <stdlib.h> int main() { FILE* fptr; fptr = fopen("file.txt", "w"); if (fptr == NULL) { printf("The file is not opened. The program will “); exit(0); } else { printf("The file is created Successfully."); } return 0; } Creating a file
  • 11. The file read operation in C can be performed using functions fscanf() or fgets(). Similar to scanf and gets functions, but fscanf and fgets have file pointer as parameter. There are also other functions we can use to read from a file Reading from file fscanf()- Use formatted string and variable arguments list to take input from a file. fgets() - Input the whole line from the file. fgetc() - Reads a single character from the file. fgetw() - Reads a number from a file. fread() - Reads the specified amount of bytes to the binary file.
  • 12. All file reading functions return EOF (End Of File) when they reach the end of the file while reading. After reading a particular part of the file, the file pointer will be automatically moved to the end of the last read character. Reading from file FILE * fptr; fptr = fopen(“fileName.txt”, “r”); fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year); char c = fgetc(fptr);
  • 13. #include <stdio.h> #include <string.h> int main() { FILE* filePointer; char dataToBeRead[50]; filePointer = fopen("Hi.txt", "r"); if (filePointer == NULL) { printf("Hi.txt file failed to open."); } else { printf("The file is now opened.n"); Reading from TEXT file while (fgets(dataToBeRead, 50, filePointer) != NULL) { printf("%sn", dataToBeRead); } //while loop ending fclose(filePointer); printf("nData read successfully and file is now closed."); } //else body ending return 0; } //main body ending.
  • 14. #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE* fptr; if ((fptr = fopen("D:program.bin", "rb")) == NULL) { printf("Error! opening file"); exit(1); } Reading from BINARY file for (n = 1; n < 5; ++n) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %dtn2: %dtn3: %dn", num.n1, num.n2, num.n3); } fclose(fptr); return 0; }
  • 15. The file write operations can be performed by the functions fprintf() and fputs() with similarities to read operations. Writing to a file fprintf() - Use formatted string and variable arguments list to print output to the file. fputs() – Prints the whole line in the file and new line at the end. fputc() – Prints a single character into the file. fputw() – Prints a number to the file. fwrite() – Writes the specified bytes of data from a binary file.
  • 16. #include <stdio.h> #include <string.h> int main() { FILE* filePointer; char dataToBeWritten[50] = "Hi welcome to C progrmming n File Handling nConcepts"; filePointer = fopen("Hi.txt", "w"); //filePointer = fopen("D:Hi.c", "w"); if (filePointer == NULL) { printf("H.c file failed to open."); } Writing to TEXT file else { if (strlen(dataToBeWritten) > 0) { fputs(dataToBeWritten, filePointer); fputs("n", filePointer); } fclose(filePointer); printf("Data written and file is now closed."); } return 0; }
  • 17. #include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int n; struct threeNum num; FILE* fptr; if ((fptr = fopen("D:program.bin", "wb")) == NULL) { printf("Error! opening file"); exit(1); } Writing to BINARY file int flag = 0; for (n = 1; n < 5; ++n) { num.n1 = n; num.n2 = 5 * n; num.n3 = 5 * n + 1; flag = fwrite(&num, sizeof(struct threeNum), 1, fptr); } if (!flag) { printf("Write Operation Failure"); } else { printf("Write Operation Successful"); } // fclose(fptr); return 0; }
  • 18. The fclose() function is used to close the file. After successful file operations, close a file to remove it from the memory. Closing a file FILE *fptr ; fptr= fopen(“fileName.txt”, “w”); //perform some operations. fclose(fptr);
  • 19.  If file has multiple records and we need to access a particular record (at a specific position), use fseek() which provides an easier way to get to the required data. We use fseek() Instead of looping through all the records before it to get the record which consumes more memory and operational time. fseek() helps to reduce memory consumption and operational time. fseek() function in C seeks the cursor to the given record in the file. int fseek(FILE *fptr, long int offset, int pos) Other File Operations - fseek()
  • 20.  Its used to bring the file pointer to the beginning of the file. It can be used in place of fseek() when you want the file pointer at the start or beginning of the file (BOF). rewind (file_pointer); Other File Operations - rewind() #include <stdio.h> int main() { FILE* fptr; fptr = fopen("file.txt", "w+"); fprintf(fptr, “Welcome to C Programmingn"); rewind(fptr); char buf[50]; fscanf(fptr, "%[^n]s", buf); printf("%s", buf); return 0; }
  • 21.  Its used to find out the position of the file pointer in the file with respect to starting of the file. long ftell (file_pointer); Other File Operations - ftell() #include <stdio.h> int main() { FILE* fp = fopen(“file.txt", "r"); char string[20]; fscanf(fp, "%s", string); printf("%ld", ftell(fp)); return 0; }
  • 22. • Create Student structure (id,name,mark1,mark2,mark3,total,avg), read Student details from the user except total and average, calculate the total & average and write the student structure to file. • Read the student file in the structure and display each student details line by line. • Write program to merge two input files data in to third file and display the third file content. Exercises
  • 23. • The arguments passed from command line are called command line arguments. These arguments are handled by main() function. • To support command line argument, programmer needs to change the structure of main() function as int main(int argc, char *argv[] ) • Here, argc counts the number of arguments. It counts the file name as the first argument. • The argv[] contains the total arguments. The first argument is the file name always. Command Line Arguments
  • 24. #include<stdio.h> void main(int argc, char *argv[] ) { printf("Program name is: %sn", argv[0]); if(argc < 2) { printf("No argument passed through command line.n"); } else { printf("First argument is: %sn", argv[1]); } } Example
  • 25. #include<stdio.h> #include<stdlib.h> void main(int argc, char *argv[] ) { if(argc >= 2) { int i=1,sum=0; while(i <= argc) { sum+=atol(argv[i]); //atol Is the function from stdlib.h to convert str to int. i++; } printf("Sum of commandline Arguments are : %dn", sum); } } Example – Sum of digits using CLI
  • 27. What Questions do you have 27

Editor's Notes

  • #7: When we calculate the size of the struct student, size comes to be 6 bytes, but this answer is incorrect.
  • #8: When we calculate the size of the struct student, size comes to be 6 bytes, but this answer is incorrect.
  • #9: When we calculate the size of the struct student, size comes to be 6 bytes, but this answer is incorrect.