SlideShare a Scribd company logo
Files
Programming for
Problem Solving using C
Mr. R. Prathap Kumar
Department of Computer Science
Engineering
Files
Syllabus
FILES: Introduction to files, Streams, I/O
using streams – opening a stream, closing
stream; Character input, Character output,
File position indicator, End of file and errors,
Line input and line output, Formatted I/O,
Block input and output, File type, Files and
command line arguments.
Files
Files:
 A file is an external collection of related data
treated as a unit.
 The aim of a file is to keep a record of data.
 Since the contents of primary memory lost
when the computer is shut down, we need
files to store data in a more permanent form.
 Additionally, the collection of data is often
too large to reside entirely in main memory
at one time.
Files
 Files are stored in auxiliary or secondary
storage devices.
 The two most common forms of secondary
storage are disk (hard disk, CD, and DVD)
and tape.
 The stdio.h header file defines the file
structure;
 FILE is predefined datatype. When we need
a file in our program, we declare it using the
FILE type.
 FILE *sp; //sp is a pointer to type FILE
Files
Streams
 Stream is a buffer. It will act as interface between
terminals (such as keyboard,monitor etc..)
 It receives or send data as sequence of byes
 There are two types of streams
1. input stream
2. output stream
 Input stream will send the data to the program by taking
from keyboard or file
 Output Stream will send the data to the monitor or file
by taking from the program
Files
Files
Text files vs Binary files:
In text files, everything is stored in terms of text
i.e. even if we store an integer 54; it will be
stored as a 2- bytes. In a text file certain
character translation may occur.
A binary file Contains data that was written in
the same format used to store internally in main
memory. For example, the integer value 1245
will be stored in 2 bytes depending on the
machine while it will require 4 bytes in a text
file.
Files
Text File Binary File
Bits represent character. Bits represent a custom data.
Less prone to get corrupt as
changes reflect as soon as the
file is opened and can easily be
undone.
Can easily get corrupted, even a
single bit change may corrupt
the file.
Can store only plain text in a
file.
Can store different types of data
(image, audio, text) in a single
file.
Mostly .txt , .dat, .c and .rtf are
used as extensions to text files.
Can have any application
defined extension .jpg,.png,.exe.
Files
Files
I/O Using streams
Files
Files
File Handling Functions
Files
Files
Files
File opening modes
Files
Files
Files
Closing file:
Files
Character Input/Output Functions
getc()/fgetc()
Character input functions read one character at a
time from a file.
putc()/fputc()
Character output functions write one character
at the time to a file
Files
Write a C program to read and write a character
from/into a file
#include<stdio.h>
main(){
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
ch=getchar();
putc(ch, fp);
fclose(fp);
Files
fp = fopen("one.txt", "r");
printf(“nThe data in the file is”);
ch=getc(fp);
printf("%c",ch);
fclose(fp);
}
Files
Write a C program to read and write text
from/into a file
#include<stdio.h>
main(){
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch=getchar())!=EOF) {
putc(ch, fp); }
fclose(fp);
Files
fp = fopen("one.txt", "r");
printf(“nThe data in the file is”);
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
Files
Write a program in C to copy a file in another
name.
#include<stdio.h>
main(){
FILE *fp1,*fp2;
char ch;
fp1 = fopen("one.txt", "w");
printf("Enter data...");
while((ch=getchar())!=EOF) {
fputc(ch, fp1); }
fclose(fp1);
Files
fp1 = fopen("one.txt", "r");
fp2 = fopen("two.txt", "w");
while((ch=fgetc(fp1))!=EOF){
fputc(ch, fp2);
printf("%c",ch);
}
printf("file coied successfully");
fclose(fp1);
fclose(fp2);
}
Files
Line Input/Output Functions
fgets()
It read one line at a time from a file.
fputs()
It write one line at the time to a file
Files
Writing File : fputs() function
Syntax:
int fputs(const char *s, FILE *stream)
Reading File : fgets() function
Syntax:
char* fgets(char *s, int n, FILE *stream)
Files
//WAP to write and read string into/from file
#include<stdio.h>
void main(){
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
fp=fopen("myfile2.txt","r");
fgets(text,200,fp);
printf("%s",text);
fclose(fp);
} Output:
hello c programming
Files
Formatting Input/Output functions:
fscanf() and fprintf()
If the file contains data in the form of digits,
real numbers, characters and strings, then
character input/output functions are not enough
as the values would be read in the form of
characters.
The syntax for these functions is:
int fscanf(FILE *fp, char *format,. . .);
int fprintf(FILE *fp, char *format,. . .);
Files
/* Write a program in C to copy a file in another
name. */
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE *fp1,*fp2;
int a,b;
fp1=fopen("one.txt", "w");
printf("Enter a and b values from key board: n");
scanf("%d%d",&a,&b); /* read from keyboard */
fprintf(fp1, "%d %d",a,b); /* write to file */
fclose(fp1);
Files
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","w");
fscanf(fp1,"%d%d",&a, &b); /* read from file */
fprintf(fp2,"A t B n");
fprintf(fp2,"%d t %d",a,b);
printf("copied successfully");
fclose(fp1);
fclose(fp2);
}
Files
File Positioning / Random-Access I/O
functions
fseek()
ftell()
rewind()
Files
fseek() function is used to move the file position
to a desired location within the file.
Syntax:
int fseek(FILE *fp, long int numbytes, int
origin);
Here, fp is a file pointer returned by a call to
fopen( ),
numbytes is the number of bytes that pointer
moves from origin, which will become the new
current position.
Files
Origin is one of the following macros:
Origin Macro Name value
Beginning of file SEEK_SET 0
Current position SEEK_CUR 1
End of file SEEK_END 2
Files
Statement Meaning
fseek(fp,00,0) Go to the beginning.
fseek(fp,00,1) Stay at current position.
fseek(fp,-l,2) Go to the end of the file,
past the last character of the file.
fseek(fp,m,0) move to (m+1)th byte in
the file.
fseek(fp,m,1) Go Forward by m bytes.
fseek(fp,-m,1) Go Backward by m bytes
from the current position.
fseek(fp,-m,2) Go Backward by m
bytes from the end.
Files
ftell():
ftell() returns the location of the current position
of the file associated with fp.
If a failure occurs, it returns –1.
long int ftell(FILE *fp);
ftell takes a file pointer as argument and return a
number of type long that corresponds to the
current position.
Files
rewind( ):
The rewind( ) function moves the file position
indicator to the start of the specified file.
void rewind(FILE *fp);
 It also clears the end-of-file and error flags
associated with file.
 This function helps us reading the file more
than once, without having to close and open
the file.
Files
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is fseek , ftell, rewind demo
using fputs", fp);
fclose(fp);
fp = fopen("myfile.txt","r+");
printf("the cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
fseek( fp,6,SEEK_SET );
Files
printf("nthe cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
rewind(fp);
printf("nthe cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
fclose(fp); } output:
the cursor position 0
character=T
the cursor position 6
character=s
the cursor position 0
character=T
Files
Block Input/output functions:
fread( ) and fwrite( ):
To read and write data types that are longer than 1
byte, the C file system provides two functions:
fread( ) and fwrite( ).
These functions allow the reading and writing of
blocks of any type of data.
size_t fread (void *buffer, size_t num_bytes,
size_t count, FILE *fp);
size_t fwrite (const void *buffer, size_t
num_bytes, size_t count, FILE *fp);
Files
 For fread( ), buffer is a pointer to a region of
memory that will receive the data from the file.
 For fwrite( ), buffer is a pointer to the
information that will be written to the file.
 The value of count determines how many items
are read or written, with each item being num
bytes in length.
 fp is a file pointer to a previously opened stream.
Files
#include<stdio.h>
main(){
struct employee{
int eid;
char name[20];
char address[20];
};
FILE *fp;
struct employee emp;
fp=fopen("one.b","wb");
printf(" enter employee id,name and address n");
scanf("%d%s%s",&emp.eid,emp.name,emp.address);
Files
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
printf(" display the employee details from
one.txt file n");
fp=fopen("one.b","rb");
fread(&emp,sizeof(emp),1,fp);
printf("Eid=%dnEname=%snAddress=%sn",e
mp.eid,emp.name,emp.address);
fclose(fp);
}
Files
Files and command line arguments.
It is a procedure of passing the arguments to the main function
from the command prompt.
/*This program reads a file specified by the user as a command
line argument and display the contents of the file on screen. */
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp; char *filename;
char ch;
Files
if (argc < 2) {
printf("Missing Filenamen"); return(1);
}
else {
filename = argv[1];
printf("Filename : %sn", filename);
}
fp = fopen(filename,"r");
Files
if ( fp!=NULL ) {
printf("File contents:n");
while ( (ch = fgetc(fp)) != EOF ) {
printf("%c",ch);
}
}
else {
printf("Failed to open the filen");
}
return(0);
}
Files
Hello.txt
Welcome to c programming
Output
$cc file1.c
$./a.out hello.txt
Welcome to c programming
Files

More Related Content

Similar to PPS-II UNIT-5 PPT.pptx

C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
File handling-c
File handling-cFile handling-c
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
Sandeepbhuma1
 
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
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar B Kute
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
File handling
File handlingFile handling
File handling
Ans Ali
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
YOGESH SINGH
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
AzanMehdi
 
file handling1
file handling1file handling1
file handling1
student
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
Osmania University
 
Unit5
Unit5Unit5
Unit5
mrecedu
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
DHARUNESHBOOPATHY
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
armaansohail9356
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 

Similar to PPS-II UNIT-5 PPT.pptx (20)

C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling-c
File handling-cFile handling-c
File handling-c
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
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
 
File management
File managementFile management
File management
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling
File handlingFile handling
File handling
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
new pdfrdfzdfzdzzzzzzzzzzzzzzzzzzzzzzzzzzgggggggggggggggggggggggggggggggggggg...
 
file handling1
file handling1file handling1
file handling1
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Unit5
Unit5Unit5
Unit5
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 

Recently uploaded

Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
National Information Standards Organization (NISO)
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Henry Hollis
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Vivekanand Anglo Vedic Academy
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
RamseyBerglund
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
nitinpv4ai
 

Recently uploaded (20)

Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.pptLevel 3 NCEA - NZ: A  Nation In the Making 1872 - 1900 SML.ppt
Level 3 NCEA - NZ: A Nation In the Making 1872 - 1900 SML.ppt
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Electric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger HuntElectric Fetus - Record Store Scavenger Hunt
Electric Fetus - Record Store Scavenger Hunt
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Bonku-Babus-Friend by Sathyajith Ray (9)
Bonku-Babus-Friend by Sathyajith Ray  (9)Bonku-Babus-Friend by Sathyajith Ray  (9)
Bonku-Babus-Friend by Sathyajith Ray (9)
 

PPS-II UNIT-5 PPT.pptx

  • 1. Files Programming for Problem Solving using C Mr. R. Prathap Kumar Department of Computer Science Engineering
  • 2. Files Syllabus FILES: Introduction to files, Streams, I/O using streams – opening a stream, closing stream; Character input, Character output, File position indicator, End of file and errors, Line input and line output, Formatted I/O, Block input and output, File type, Files and command line arguments.
  • 3. Files Files:  A file is an external collection of related data treated as a unit.  The aim of a file is to keep a record of data.  Since the contents of primary memory lost when the computer is shut down, we need files to store data in a more permanent form.  Additionally, the collection of data is often too large to reside entirely in main memory at one time.
  • 4. Files  Files are stored in auxiliary or secondary storage devices.  The two most common forms of secondary storage are disk (hard disk, CD, and DVD) and tape.  The stdio.h header file defines the file structure;  FILE is predefined datatype. When we need a file in our program, we declare it using the FILE type.  FILE *sp; //sp is a pointer to type FILE
  • 5. Files Streams  Stream is a buffer. It will act as interface between terminals (such as keyboard,monitor etc..)  It receives or send data as sequence of byes  There are two types of streams 1. input stream 2. output stream  Input stream will send the data to the program by taking from keyboard or file  Output Stream will send the data to the monitor or file by taking from the program
  • 7. Files Text files vs Binary files: In text files, everything is stored in terms of text i.e. even if we store an integer 54; it will be stored as a 2- bytes. In a text file certain character translation may occur. A binary file Contains data that was written in the same format used to store internally in main memory. For example, the integer value 1245 will be stored in 2 bytes depending on the machine while it will require 4 bytes in a text file.
  • 8. Files Text File Binary File Bits represent character. Bits represent a custom data. Less prone to get corrupt as changes reflect as soon as the file is opened and can easily be undone. Can easily get corrupted, even a single bit change may corrupt the file. Can store only plain text in a file. Can store different types of data (image, audio, text) in a single file. Mostly .txt , .dat, .c and .rtf are used as extensions to text files. Can have any application defined extension .jpg,.png,.exe.
  • 11. Files
  • 13. Files
  • 14. Files
  • 16. Files
  • 17. Files
  • 19. Files Character Input/Output Functions getc()/fgetc() Character input functions read one character at a time from a file. putc()/fputc() Character output functions write one character at the time to a file
  • 20. Files Write a C program to read and write a character from/into a file #include<stdio.h> main(){ FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data..."); ch=getchar(); putc(ch, fp); fclose(fp);
  • 21. Files fp = fopen("one.txt", "r"); printf(“nThe data in the file is”); ch=getc(fp); printf("%c",ch); fclose(fp); }
  • 22. Files Write a C program to read and write text from/into a file #include<stdio.h> main(){ FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data..."); while( (ch=getchar())!=EOF) { putc(ch, fp); } fclose(fp);
  • 23. Files fp = fopen("one.txt", "r"); printf(“nThe data in the file is”); while((ch=getc(fp))!=EOF) printf("%c",ch); fclose(fp); }
  • 24. Files Write a program in C to copy a file in another name. #include<stdio.h> main(){ FILE *fp1,*fp2; char ch; fp1 = fopen("one.txt", "w"); printf("Enter data..."); while((ch=getchar())!=EOF) { fputc(ch, fp1); } fclose(fp1);
  • 25. Files fp1 = fopen("one.txt", "r"); fp2 = fopen("two.txt", "w"); while((ch=fgetc(fp1))!=EOF){ fputc(ch, fp2); printf("%c",ch); } printf("file coied successfully"); fclose(fp1); fclose(fp2); }
  • 26. Files Line Input/Output Functions fgets() It read one line at a time from a file. fputs() It write one line at the time to a file
  • 27. Files Writing File : fputs() function Syntax: int fputs(const char *s, FILE *stream) Reading File : fgets() function Syntax: char* fgets(char *s, int n, FILE *stream)
  • 28. Files //WAP to write and read string into/from file #include<stdio.h> void main(){ FILE *fp; char text[300]; fp=fopen("myfile2.txt","w"); fputs("hello c programming",fp); fclose(fp); fp=fopen("myfile2.txt","r"); fgets(text,200,fp); printf("%s",text); fclose(fp); } Output: hello c programming
  • 29. Files Formatting Input/Output functions: fscanf() and fprintf() If the file contains data in the form of digits, real numbers, characters and strings, then character input/output functions are not enough as the values would be read in the form of characters. The syntax for these functions is: int fscanf(FILE *fp, char *format,. . .); int fprintf(FILE *fp, char *format,. . .);
  • 30. Files /* Write a program in C to copy a file in another name. */ #include<stdio.h> #include<stdlib.h> int main() { FILE *fp1,*fp2; int a,b; fp1=fopen("one.txt", "w"); printf("Enter a and b values from key board: n"); scanf("%d%d",&a,&b); /* read from keyboard */ fprintf(fp1, "%d %d",a,b); /* write to file */ fclose(fp1);
  • 31. Files fp1=fopen("one.txt","r"); fp2=fopen("two.txt","w"); fscanf(fp1,"%d%d",&a, &b); /* read from file */ fprintf(fp2,"A t B n"); fprintf(fp2,"%d t %d",a,b); printf("copied successfully"); fclose(fp1); fclose(fp2); }
  • 32. Files File Positioning / Random-Access I/O functions fseek() ftell() rewind()
  • 33. Files fseek() function is used to move the file position to a desired location within the file. Syntax: int fseek(FILE *fp, long int numbytes, int origin); Here, fp is a file pointer returned by a call to fopen( ), numbytes is the number of bytes that pointer moves from origin, which will become the new current position.
  • 34. Files Origin is one of the following macros: Origin Macro Name value Beginning of file SEEK_SET 0 Current position SEEK_CUR 1 End of file SEEK_END 2
  • 35. Files Statement Meaning fseek(fp,00,0) Go to the beginning. fseek(fp,00,1) Stay at current position. fseek(fp,-l,2) Go to the end of the file, past the last character of the file. fseek(fp,m,0) move to (m+1)th byte in the file. fseek(fp,m,1) Go Forward by m bytes. fseek(fp,-m,1) Go Backward by m bytes from the current position. fseek(fp,-m,2) Go Backward by m bytes from the end.
  • 36. Files ftell(): ftell() returns the location of the current position of the file associated with fp. If a failure occurs, it returns –1. long int ftell(FILE *fp); ftell takes a file pointer as argument and return a number of type long that corresponds to the current position.
  • 37. Files rewind( ): The rewind( ) function moves the file position indicator to the start of the specified file. void rewind(FILE *fp);  It also clears the end-of-file and error flags associated with file.  This function helps us reading the file more than once, without having to close and open the file.
  • 38. Files #include <stdio.h> main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is fseek , ftell, rewind demo using fputs", fp); fclose(fp); fp = fopen("myfile.txt","r+"); printf("the cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); fseek( fp,6,SEEK_SET );
  • 39. Files printf("nthe cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); rewind(fp); printf("nthe cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); fclose(fp); } output: the cursor position 0 character=T the cursor position 6 character=s the cursor position 0 character=T
  • 40. Files Block Input/output functions: fread( ) and fwrite( ): To read and write data types that are longer than 1 byte, the C file system provides two functions: fread( ) and fwrite( ). These functions allow the reading and writing of blocks of any type of data. size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);
  • 41. Files  For fread( ), buffer is a pointer to a region of memory that will receive the data from the file.  For fwrite( ), buffer is a pointer to the information that will be written to the file.  The value of count determines how many items are read or written, with each item being num bytes in length.  fp is a file pointer to a previously opened stream.
  • 42. Files #include<stdio.h> main(){ struct employee{ int eid; char name[20]; char address[20]; }; FILE *fp; struct employee emp; fp=fopen("one.b","wb"); printf(" enter employee id,name and address n"); scanf("%d%s%s",&emp.eid,emp.name,emp.address);
  • 43. Files fwrite(&emp,sizeof(emp),1,fp); fclose(fp); printf(" display the employee details from one.txt file n"); fp=fopen("one.b","rb"); fread(&emp,sizeof(emp),1,fp); printf("Eid=%dnEname=%snAddress=%sn",e mp.eid,emp.name,emp.address); fclose(fp); }
  • 44. Files Files and command line arguments. It is a procedure of passing the arguments to the main function from the command prompt. /*This program reads a file specified by the user as a command line argument and display the contents of the file on screen. */ #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; char *filename; char ch;
  • 45. Files if (argc < 2) { printf("Missing Filenamen"); return(1); } else { filename = argv[1]; printf("Filename : %sn", filename); } fp = fopen(filename,"r");
  • 46. Files if ( fp!=NULL ) { printf("File contents:n"); while ( (ch = fgetc(fp)) != EOF ) { printf("%c",ch); } } else { printf("Failed to open the filen"); } return(0); }
  • 47. Files Hello.txt Welcome to c programming Output $cc file1.c $./a.out hello.txt Welcome to c programming
  • 48. Files