SlideShare a Scribd company logo
File
A file represents a sequence of bytes, regardless of it being a text file or a binary file. When a
program is terminated, the entire data is lost. Storing in a file will preserve your data even if the
program terminates. It is easy to move the data from one computer to another without any
changes. When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and the program.
FILE *fp; // *fp – file pointer variable
Types of Files
There are two types of files
 Text files
 Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad. When you open those files, you'll see all the contents within the file as plain
text. It is easy to edit or delete the contents. They take minimum effort to maintain, are easily
readable, and provide the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in the computer. Instead of storing data in plain text, they
store it in the binary form (0's and 1's). They can hold a higher amount of data, are not readable
easily, and provides better security than text files.
File Operations
1) Opening a file:
Opening a file is performed using the fopen() function defined in the stdio.h header file.
The syntax for opening a file in standard I/O is:
FILE *fp
fp = fopen("filename","mode");
File Opening Mode
Sl. No Mode Description
1 r Opens an existing text file for reading purpose.
2 w
Opens a text file for writing. If it does not exist, then a new file is
created. Here your program will start writing content from the
beginning of the file.
3 a
Opens a text file for writing in appending mode. If it does not exist,
then a new file is created. Here your program will start appending
content in the existing file content.
4 r+ Opens a text file for both reading and writing.
5 w+
Opens a text file for both reading and writing. It first truncates the
file to zero length if it exists, otherwise creates a file if it does not
exist.
6 a+
Opens a text file for both reading and writing. It creates the file if it
does not exist. The reading will start from the beginning but writing
can only be appended.
File Location
We can provide the relative address of the file location or absolute address of the file. Consider
your working directory is C:CPTest . Now you want to open a file hello.c in read mode. Two
ways to provide the file location are as given below:
fp =
fopen("hello.c","r"); OR
fp = fopen("C:CPTesthello.c","r")
2. Closing a file
The file (both text and binary) should be closed after reading/writing. Closing a file is performed
using the fclose() function.
fclose(fp);
Here, fp is a file pointer associated with the file to be closed.
3. Reading and writing to a file
Sl. No Function Name Description Syntax
1 fgetc To read a character from a file ch = fgetc(fp)
2 fputc To write a character to a file fputc(ch,fp)
3 fscanf To read numbers, string from a file fscanf(fp,"%d",&n)
4 fprintf To write numbers, strings to a file fprintf(fp,"%d",n)
5 fread To read binary content from a file. It
is used to read structure content.
Refer Note
6 fwrite To write as binary content to a file. Refer Note
Note:
1) The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.
2) To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
 Address of data to be written in the disk
 Size of data to be written in the disk
 Number of such type of data
 Pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);
3) Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);
feof()
The C library function int feof(FILE *stream) tests the end-of-file indicator for the given
stream. This function returns a non-zero value when End-of-File indicator associated with the
stream is set, else zero is returned.
Random Access to a file
1) fseek()
If you have many records inside a file and need to access a record at a specific position, you need
to loop through all the records before it to get the record. This will waste a lot of memory and
operation time. An easier way to get to the required data can be achieved using fseek().
fseek(FILE * stream, long int offset, int pos);
The first parameter stream is the pointer to the file. The second parameter is the position of the
record to be found, and the third parameter specifies the location where the offset starts.
Different positions in fseek()
Position Meaning
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.
2) ftell()
ftell() in C is used to find out the position of file pointer in the file with respect to starting of the
file.
Syntax of ftell() is:
ftell(FILE *pointer)
Examples Programs
1) Write a program to display the content of a file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("test.txt","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}
Content of test.txt
Hello, Welcome to C Programming Lectures.
Output
Hello, Welcome to C Programming Lectures.
2) Write a program to count numbers of vowels in a given file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int countV=0;
fp = fopen("test.txt","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
if(ch == 'a' || ch == 'A' || ch=='e'
ch=='E' || ch == 'I' || ch == 'i' ||
ch == 'O' || ch=='o' || ch == 'U' ||
ch == 'u')
{
countV++;
}
}
printf("Count of Vowels=%d",countV);
fclose(fp);
}
Content of test.txt
Hello, Welcome to C Programming Lectures.
Output
Count of Vowels=12
3) Write a program to copy the content of file to another.
#include<stdio.h>
void main()
{
FILE *f1,*f2;
char ch;
f1 = fopen("test.txt","r");
f2 = fopen("copy.txt","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f2);
}
printf("Successfully Copied");
fclose(f1);
fclose(f2);
}
Content of test.txt
Hello, Welcome to C Programming Lectures.
Output
Successfully Copied
Content of copy.txt
Hello, Welcome to C Programming Lectures.
4) Write a program to merge the content of two files.
#include<stdio.h>
void main()
{
FILE *f1,*f2,*f3;
char ch;
f1 = fopen("file1.txt","r");
f2 = fopen("file2.txt","r");
f3 = fopen("merge.txt","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f3);
}
while(feof(f2) == 0)
{
ch=fgetc(f2);
fputc(ch,f3);
}
printf("Successfully Merged");
}
Content of file1.txt
Hello, Welcome to C Programming Lectures.
Content of file2.txt
C is very easy to learn.
Output
Successfully Merged
Content of merge.txt
Hello, Welcome to C Programming Lectures. C is very easy to learn.
5) Write a program to read numbers from a file and display the largest number.
#include<stdio.h>
void main()
{
FILE *f1;
int large,num;
f1 = fopen("number.txt","r");
fscanf(f1,"%d",&large); // setting first element as largest element
while(feof(f1) == 0)
{
fscanf(f1,"%d",&num);
if(large<num)
{
large= num;
}
}
fclose(f1);
printf("Largest element = %d",large);
}
Content of number.txt
15 21 7 29 36 78 67 56 10
Output
Largest element = 78
6) Consider you are a content writer in Wikipedia. You are the person who write the known facts
about APJ Abdul Kalam. After his death, you need to change all is to was. Write a program to
replace all is’ to was’ to a new file.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
char str[30];
f1 = fopen("apj.txt","r");
f2 = fopen("new.txt","w");
fscanf(f1,"%s",str);
while(feof(f1) == 0)
{
if(strcmp(str,"is")==0)
fprintf(f2,"was A");
else
fprintf(f2,"%s ",str);
fscanf(f1,"%s",str);
}
fclose(f1);
fclose(f2);
printf("Replaced String Sucessfullyn");
}
7) Write a program to reverse each content of file to another.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
char str[30],rev[30];
int i,j;
f1 = fopen("test.txt","r");
f2 = fopen("new.txt","w");
while(feof(f1) == 0)
{
fscanf(f1,"%s",str);
j=0;
for(i=strlen(str)-1;i>=0;i--)
{
rev[j]=str[i];
j++;
}
rev[j]='0';
fprintf(f2,"%s ",rev);
}
fclose(f1);
fclose(f2);
}
Content of test.txt
Welcome to C programming
Content of new.txt after execution
emocleW ot C gnimmargorp
8) Write a program to copy the content of a file to another in reverse order.
#include<stdio.h>
void main()
{
FILE *f1,*f2;
int count,begin,end;
char ch,i;
f1 = fopen("test.txt","r");
f2 = fopen("new.txt","w");
// Code to find count of characters in a file.
begin = ftell(f1);
fseek(f1, -1, SEEK_END);
end = ftell(f1);
count = end - begin; // Count of characters.
printf("Count of characters=%d",count);
// Copy the content of file in reverse order
i=-1;
while (count != -1)
{
ch = fgetc(f1);
fputc(ch, f2);
i--;
fseek(f1, i, SEEK_END); // shifts the pointer to the previous character
count--;
}
fclose(f1);
fclose(f2);
}
9) Write a program to count number of words and lines in a file.
#include<stdio.h>
#include<string.h>
void main()
{
FILE *f1,*f2;
int countW=0,countL=0;
char ch;
f1 = fopen("test.txt","r");
while (feof(f1) == 0 )
{
ch = fgetc(f1);
if(ch == ' ')
countW++;
if(ch == 'n')
countL++;
}
printf("Count of words = %dn",countW);
printf("Count of Lines = %d",countL);
fclose(f1);
}
Content of test.txt
Welcome to C programming.
C is very easy to learn
Output
Count of words = 4
Count of Lines = 2
10) Write a program to append some data to already existing file.
#include<stdio.h>
void main()
{
FILE *f1;
char str[30];
f1 = fopen("test.txt","a");
printf("Enter the string:");
gets(str);
fprintf(f1,"%s",str);
fclose(f1);
}
Ad

More Related Content

What's hot (19)

File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
Gaurav Garg
 
File operations in c
File operations in cFile operations in c
File operations in c
baabtra.com - No. 1 supplier of quality freshers
 
File handling in c
File handling in c File handling in c
File handling in c
Vikash Dhal
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
Sonya Akter Rupa
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
웅식 전
 
file
filefile
file
teach4uin
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
File handling in c
File handling in cFile handling in c
File handling in c
baabtra.com - No. 1 supplier of quality freshers
 
File handling in C
File handling in CFile handling in C
File handling in C
Kamal Acharya
 
Chap 12(files)
Chap 12(files)Chap 12(files)
Chap 12(files)
Bangabandhu Sheikh Mujibur Rahman Science and Technology University
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
Felix Z. Hoffmann
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
Harish Kamat
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
Harish Gyanani
 
Unit 8
Unit 8Unit 8
Unit 8
Keerthi Mutyala
 
Files in C
Files in CFiles in C
Files in C
Prabu U
 
Php files
Php filesPhp files
Php files
kalyani66
 

Similar to Module 5 file cp (20)

Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
VenkataRangaRaoKommi1
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
4 text file
4 text file4 text file
4 text file
hasan Mohammad
 
File Organization
File OrganizationFile Organization
File Organization
RAMPRAKASH REDDY ARAVA
 
File handling-c
File handling-cFile handling-c
File handling-c
CGC Technical campus,Mohali
 
File management
File managementFile management
File management
sumathiv9
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
eShikshak
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
Bern Jamie
 
Handout#01
Handout#01Handout#01
Handout#01
Sunita Milind Dol
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
File management
File managementFile management
File management
sumathiv9
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
eShikshak
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
Bern Jamie
 
Ad

More from Amarjith C K (20)

E paper technologies
E paper technologiesE paper technologies
E paper technologies
Amarjith C K
 
Module 2
Module 2Module 2
Module 2
Amarjith C K
 
module 1
module 1module 1
module 1
Amarjith C K
 
Module 2
Module 2Module 2
Module 2
Amarjith C K
 
Module-4
Module-4Module-4
Module-4
Amarjith C K
 
2
22
2
Amarjith C K
 
New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49New doc 2020 03-28 09.51.49
New doc 2020 03-28 09.51.49
Amarjith C K
 
Mat102 module iv
Mat102  module ivMat102  module iv
Mat102 module iv
Amarjith C K
 
Mat102 module 5(text )
Mat102   module 5(text )Mat102   module 5(text )
Mat102 module 5(text )
Amarjith C K
 
Mat 102 module iv
Mat 102 module ivMat 102 module iv
Mat 102 module iv
Amarjith C K
 
New doc 2020 03-19 12.05.31
New doc 2020 03-19 12.05.31New doc 2020 03-19 12.05.31
New doc 2020 03-19 12.05.31
Amarjith C K
 
New doc 2020 03-23 14.09.06
New doc 2020 03-23 14.09.06New doc 2020 03-23 14.09.06
New doc 2020 03-23 14.09.06
Amarjith C K
 
New doc 2020 03-23 16.20.34
New doc 2020 03-23 16.20.34New doc 2020 03-23 16.20.34
New doc 2020 03-23 16.20.34
Amarjith C K
 
New doc 2020 03-23 17.08.57
New doc 2020 03-23 17.08.57New doc 2020 03-23 17.08.57
New doc 2020 03-23 17.08.57
Amarjith C K
 
Unit 03 esl
Unit 03 eslUnit 03 esl
Unit 03 esl
Amarjith C K
 
Module-5
Module-5Module-5
Module-5
Amarjith C K
 
Module-4
Module-4Module-4
Module-4
Amarjith C K
 
Module 3
Module 3Module 3
Module 3
Amarjith C K
 
Mat102 module v
Mat102  module vMat102  module v
Mat102 module v
Amarjith C K
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
Amarjith C K
 
Ad

Recently uploaded (20)

IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 

Module 5 file cp

  • 1. File A file represents a sequence of bytes, regardless of it being a text file or a binary file. When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. It is easy to move the data from one computer to another without any changes. When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and the program. FILE *fp; // *fp – file pointer variable Types of Files There are two types of files  Text files  Binary files 1. Text files Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad. When you open those files, you'll see all the contents within the file as plain text. It is easy to edit or delete the contents. They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space. 2. Binary files Binary files are mostly the .bin files in the computer. Instead of storing data in plain text, they store it in the binary form (0's and 1's). They can hold a higher amount of data, are not readable easily, and provides better security than text files. File Operations 1) Opening a file: Opening a file is performed using the fopen() function defined in the stdio.h header file. The syntax for opening a file in standard I/O is: FILE *fp fp = fopen("filename","mode");
  • 2. File Opening Mode Sl. No Mode Description 1 r Opens an existing text file for reading purpose. 2 w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. 3 a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. 4 r+ Opens a text file for both reading and writing. 5 w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. 6 a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. File Location We can provide the relative address of the file location or absolute address of the file. Consider your working directory is C:CPTest . Now you want to open a file hello.c in read mode. Two ways to provide the file location are as given below: fp = fopen("hello.c","r"); OR fp = fopen("C:CPTesthello.c","r") 2. Closing a file The file (both text and binary) should be closed after reading/writing. Closing a file is performed using the fclose() function.
  • 3. fclose(fp); Here, fp is a file pointer associated with the file to be closed. 3. Reading and writing to a file Sl. No Function Name Description Syntax 1 fgetc To read a character from a file ch = fgetc(fp) 2 fputc To write a character to a file fputc(ch,fp) 3 fscanf To read numbers, string from a file fscanf(fp,"%d",&n) 4 fprintf To write numbers, strings to a file fprintf(fp,"%d",n) 5 fread To read binary content from a file. It is used to read structure content. Refer Note 6 fwrite To write as binary content to a file. Refer Note Note: 1) The only difference is that fprint() and fscanf() expects a pointer to the structure FILE. 2) To write into a binary file, you need to use the fwrite() function. The functions take four arguments:  Address of data to be written in the disk  Size of data to be written in the disk  Number of such type of data  Pointer to the file where you want to write. fwrite(addressData, sizeData, numbersData, pointerToFile); 3) Function fread() also take 4 arguments similar to the fwrite() function as above. fread(addressData, sizeData, numbersData, pointerToFile); feof() The C library function int feof(FILE *stream) tests the end-of-file indicator for the given stream. This function returns a non-zero value when End-of-File indicator associated with the stream is set, else zero is returned.
  • 4. Random Access to a file 1) fseek() If you have many records inside a file and need to access a record at a specific position, you need to loop through all the records before it to get the record. This will waste a lot of memory and operation time. An easier way to get to the required data can be achieved using fseek(). fseek(FILE * stream, long int offset, int pos); The first parameter stream is the pointer to the file. The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts. Different positions in fseek() Position Meaning SEEK_SET Starts the offset from the beginning of the file. SEEK_END Starts the offset from the end of the file. SEEK_CUR Starts the offset from the current location of the cursor in the file. 2) ftell() ftell() in C is used to find out the position of file pointer in the file with respect to starting of the file. Syntax of ftell() is: ftell(FILE *pointer) Examples Programs 1) Write a program to display the content of a file. #include<stdio.h> void main() { FILE *fp; char ch; fp = fopen("test.txt","r"); while(feof(fp) == 0)
  • 5. { ch=fgetc(fp); printf("%c",ch); } fclose(fp); } Content of test.txt Hello, Welcome to C Programming Lectures. Output Hello, Welcome to C Programming Lectures. 2) Write a program to count numbers of vowels in a given file. #include<stdio.h> void main() { FILE *fp; char ch; int countV=0; fp = fopen("test.txt","r"); while(feof(fp) == 0) { ch=fgetc(fp); if(ch == 'a' || ch == 'A' || ch=='e' ch=='E' || ch == 'I' || ch == 'i' || ch == 'O' || ch=='o' || ch == 'U' || ch == 'u') { countV++; } } printf("Count of Vowels=%d",countV); fclose(fp); } Content of test.txt Hello, Welcome to C Programming Lectures. Output Count of Vowels=12
  • 6. 3) Write a program to copy the content of file to another.
  • 7. #include<stdio.h> void main() { FILE *f1,*f2; char ch; f1 = fopen("test.txt","r"); f2 = fopen("copy.txt","w"); while(feof(f1) == 0) { ch=fgetc(f1); fputc(ch,f2); } printf("Successfully Copied"); fclose(f1); fclose(f2); } Content of test.txt Hello, Welcome to C Programming Lectures. Output Successfully Copied Content of copy.txt Hello, Welcome to C Programming Lectures. 4) Write a program to merge the content of two files. #include<stdio.h> void main() { FILE *f1,*f2,*f3; char ch; f1 = fopen("file1.txt","r"); f2 = fopen("file2.txt","r"); f3 = fopen("merge.txt","w"); while(feof(f1) == 0) { ch=fgetc(f1); fputc(ch,f3); } while(feof(f2) == 0) {
  • 9. printf("Successfully Merged"); } Content of file1.txt Hello, Welcome to C Programming Lectures. Content of file2.txt C is very easy to learn. Output Successfully Merged Content of merge.txt Hello, Welcome to C Programming Lectures. C is very easy to learn. 5) Write a program to read numbers from a file and display the largest number. #include<stdio.h> void main() { FILE *f1; int large,num; f1 = fopen("number.txt","r"); fscanf(f1,"%d",&large); // setting first element as largest element while(feof(f1) == 0) { fscanf(f1,"%d",&num); if(large<num) { large= num; } } fclose(f1); printf("Largest element = %d",large); } Content of number.txt 15 21 7 29 36 78 67 56 10 Output Largest element = 78
  • 10. 6) Consider you are a content writer in Wikipedia. You are the person who write the known facts about APJ Abdul Kalam. After his death, you need to change all is to was. Write a program to replace all is’ to was’ to a new file. #include<stdio.h> #include<string.h> void main() { FILE *f1,*f2; char str[30]; f1 = fopen("apj.txt","r"); f2 = fopen("new.txt","w"); fscanf(f1,"%s",str); while(feof(f1) == 0) { if(strcmp(str,"is")==0) fprintf(f2,"was A"); else fprintf(f2,"%s ",str); fscanf(f1,"%s",str); } fclose(f1); fclose(f2); printf("Replaced String Sucessfullyn"); } 7) Write a program to reverse each content of file to another. #include<stdio.h> #include<string.h> void main() { FILE *f1,*f2; char str[30],rev[30]; int i,j; f1 = fopen("test.txt","r"); f2 = fopen("new.txt","w"); while(feof(f1) == 0)
  • 12. for(i=strlen(str)-1;i>=0;i--) { rev[j]=str[i]; j++; } rev[j]='0'; fprintf(f2,"%s ",rev); } fclose(f1); fclose(f2); } Content of test.txt Welcome to C programming Content of new.txt after execution emocleW ot C gnimmargorp 8) Write a program to copy the content of a file to another in reverse order. #include<stdio.h> void main() { FILE *f1,*f2; int count,begin,end; char ch,i; f1 = fopen("test.txt","r"); f2 = fopen("new.txt","w"); // Code to find count of characters in a file. begin = ftell(f1); fseek(f1, -1, SEEK_END); end = ftell(f1); count = end - begin; // Count of characters. printf("Count of characters=%d",count); // Copy the content of file in reverse order i=-1; while (count != -1) { ch = fgetc(f1); fputc(ch, f2); i--;
  • 13. fseek(f1, i, SEEK_END); // shifts the pointer to the previous character count--;
  • 14. } fclose(f1); fclose(f2); } 9) Write a program to count number of words and lines in a file. #include<stdio.h> #include<string.h> void main() { FILE *f1,*f2; int countW=0,countL=0; char ch; f1 = fopen("test.txt","r"); while (feof(f1) == 0 ) { ch = fgetc(f1); if(ch == ' ') countW++; if(ch == 'n') countL++; } printf("Count of words = %dn",countW); printf("Count of Lines = %d",countL); fclose(f1); } Content of test.txt Welcome to C programming. C is very easy to learn Output Count of words = 4 Count of Lines = 2 10) Write a program to append some data to already existing file. #include<stdio.h> void main() {
  • 15. FILE *f1; char str[30]; f1 = fopen("test.txt","a");