SlideShare a Scribd company logo
1 of 33
Submitted by
K.Lalithambiga Msc(cs),
N.S.College of Arts & Science.
File management
Introduction
Defining and Opening a File
Closing a File
Input/output operations on File
Error Handling During I/O Operation
Random Access to Files
Command Line Arguments
Introduction
 A file represents a sequence of bytes on the disk where a
group of related data is stored.
 File is created for permanent storage of data. It is a ready
made structure.
 Real life problems involve large volume of data and in such
cases, the console oriented I/O operations pose two major
problems
It becomes cumbersome and time consuming to handle large
volumes of data through terminals.
The entire data is lost when either the program is terminated or
computer is turned off .
Basic File operations .They are,
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
There are two distinct ways to perform file operations in c.
The first one is known as the low-level I/O and used UNIX
system calls.
The second method is know n as the high-level I/O operation
and uses function in C’s standard I/O library
It is used for store a data permanently in computer. Using this
concept we can store our data in Secondary memory (Hard disk).
High level I/O function
S.No
Function Name Operation
1
fopen() Creates a new file for use
Opens a new existing file for use
2
fclose() Closes a file which has been opened for use
3
getc() Reads a character from a file
4
putc() Writes a character to a file
5
fprintf() Writes a set of data values to a file
6
fscanf() Reads a set of data values from a file
7 getw() Reads a integer from a file
8 putw() Writes an integer to the file
9 fseek() Sets the position to a desired point in the file
10 ftell() Gives the current position in the file
11 rewind() Sets the position to the beginning of the file
Defining AND OPENING file
• To store data in a file in the secondary memory specify
certain things about the file to the operating system. They
include ,
• Filename is a string of characters that makeup a valid for the
operating system.
• Data structure of a file is defined as ‘File’ in the library of
standard I/O function definition .
• File is a defined data type.
• It contains two parts, a Primary name and optional period
with extension.
1.File name
2.Data structure
3. Purpose
Example:
Input .data
PROG.C
File operations
 Fopen function: The general format for declaring and opening
a file is
 The variable fp has a pointer to the data type File opens
the File name and pointer assigns an identifier to the File type
pointer fp.
 This pointer which contains all the information about the File
subsequently used as a communication link between the system
and the program.
Mode can be one the following
 r - open the file for reading only.
 w - open the file writing only.
 a - open the file for appending (adding) data to each.
FILE *fp;
Fp = fopen ( “file name”, “mode” );
File opening with example
 Both ‘file name’ and ‘mode’ are specified as string they should
be enclosed in double quotation marks (“ ”).
Example:
Where fp1,fp2 are pointer
 The ‘fp1’ is opens the File named as data for reading mode
only.
 Then ‘fp2’ is opens the File named as result for writing
mode only.
FILE * fp1, *fp2;
Fp1 = fopen (“data’’, “r”);
Fp2= fopen (“result”, “w”);
Program for file opening
Reading
#include<stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = getc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
Writing
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s",” example :");
/*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
Appending
#include <stdio.h>
int main()
{
FILE *fp ;
file = fopen("file.txt","a");
fprintf(fp,"%s"," example :");
/*append some text*/
fclose(fp);
return 0;
}
Additional modes of operation
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
Closing a file
 A File must be closed after all operations have been
completed. The general form of fclose function is
Syntax:
Example: :
 This program opens two files and closes them after all
operations on them are completed once a file is closed its file
pointer can be reused for another file.
Fclose (file pointer);
Fp1 =fopen (“input”, "W”);
Fp2 = fopen(“output”, “r”);
……….
……….
Fclose(fp1);
Fclose(fp2);
……….
Program for closing a file
#include <stdio.h>
main( )
{
FILE *fp;
char c;
funny = fopen("TENLINES.TXT", "r");
if (fp == NULL)
printf("File doesn't existn");
else
{
do
{
c = getc(fp); /* get one character from the file */
putchar(c); /* display it on the monitor */
}
while (c != EOF); /* repeat until EOF (end of file) */
}
fclose(fp);
}
getc function
The getc is used to read a character from a file that has
been opened in read mode.
Syntax:
The read a character from the file whose pointer is file
pointer and assigned the reading character to ‘C’.
The reading is terminated when getc encounter end of file
mark EOF.
Example :
File *fp;
Char c;
………….
Fp=fopen (“input”, “r”);
While(c=getc(fp)!=Eof)
Putchar ( c );
C=getc (file pointer);
Input/output operations on files
putcfunction
 The putc is used to write a character to a file that has been
opened in write mode.
Syntax:
 The read a character through to the variable and put these
character through whose file pointer is fp.
 The writing is terminated when putc encounters the end of file
mark EOF.
Example:
Putc (c,fp);
FILE *fp;
Char C;
………..
Fp=fopen(“input”, “w”);
While (c = getchar( c )!= EOF)
Putc(c, fp);
getw function
 The simplest integer oriented file I/o function is getw that has
been opened in read mode .
Syntax:
 Where read an integer value from the file whose file pointer is
fp and assigned the reading numbers to num.
 The reading is terminated when getw encounters the end of file
mark EOF.
Example :
Num =getw (fp);
FILE *fp
Int num;
……….
Fp=fopen (“input”, "r”);
While (num=getw(fp)!=EOF)
Printf(“%d”, num);
Putw function
 The simplest I/O integer oriented function is putw is used to
create an integer value to a file that has been opened in write
mode.
Syntax:
 The read a number through to the variable ‘num’ and put the
number into the file whose file pointer is fp.
 The waiting is terminted when ‘Putw’ encounters the end of
file mark Eof (i.e,num=0)
Example :
FILE *fp
Int num;
Fp=fopen (“INPUT”, "w”);
Scanf(“%d”, & num);
While (num!= fp)
Putw(num,fp);
Scanf(“%d”, & num);
Putw(num,fp);
fprintf function
 The fprintf statement is used to write data items to the file whose
file pointer is opened in the writing mode.
 ‘fprintf’ perform I/O operations an files.
Syntax:
 Where ‘fp’ is a file pointer associated with a file that has been
opened for writing.
 The control string contains output specifications for the items in the
list.
 The list may be including variable constants and strings.
Example :
 Where ‘name is an array variable of type and age is an int
variable.
fprintf (fp1, "%s %d %f”, name age,7.5);
Fprintf (fp, "control string", list);
fscanffunction
 The fscanf function is used to read data items to the file whose
pointer is opened in the reading mode.
 fscanf function performs I/O operations on files.
Syntax:
 This statement reading of the items in the list from the file
specified by fp. The control string contains input specifications
for the items in the list.
Example :
 Where “item” is an array variable of type and quantity is an int
variable.
 fscanf returns the no. of items when the end of file is reached 'i'
returns the value EOF.
fscanf (fp1, “%s %d”, item & quantity);
fscanf (fp, “control string”, list);
#include <stdio.h>
int main ()
{
char name [20];
int age, length;
FILE *fp;
fp = fopen ("test.txt","w");
fprintf (fp, "%s %d", “Fresh2refresh”, 5);
length = ftell(fp); // Cursor position is now at the end of file
/* You can use fseek(fp, 0, SEEK_END); also to move the cursor to the end of the file */
rewind (fp); // It will move cursor position to the beginning of the file
fscanf (fp, "%d", &age);
fscanf (fp, "%s", name);
fclose (fp);
printf ("Name: %s n Age: %d n",name,age);
printf ("Total number of characters in file is %d", length);
return 0;
}
OUTPUT:
Name: Fresh2refresh
Age: 5
Total number of characters in file is 15
Program for printf and scanf
Error handling during i/o operations
 It is possible that an error may occur during I/O operations on a
file. Typical error situations include:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is
opened for another type of operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.
feof function
 The feof function can be used to test for an end of file
condition .
 It takes a file pointer as an argument and returns a non-zero
integer value id all of the data from the specified file has been
read and returns zero otherwise.
Example:
 This statement gives the end of data when encountered end of
file condition.
If (feof (fp)
Printf(“end of file”);
ferror function
 The ferror function is also takes a file pointer its argument
and returns a non-zero integer.
 If an error has been detected up to that point during processing
it returns zero otherwise.
Example :
 Print the error message if the reading is not successful.
If (ferror (fp)!=0)
Printf(“file could not be open”);
Program for ferror function
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txtn");
}
clearerr(fp);
if( ferror(fp) )
{
printf("Error in reading from file : file.txtn");
}
fclose(fp);
return(0);
}
Output:
Error in reading from file : file.txt
Random access to files
 This file functions are useful to reading and writing data
sequentially.
 When we are interested in accessing only a particular part of a
file and not in reading the other parts.
 This can be achieved with the help of the functions fseek, ftell
and rewind available in the I/O library.
ftell function
 The ftell function is useful in saving the current position of a
file, which can be used later in the program .
 It takes the following form
Syntax:
 Where ‘n’ gives the relative offset (in bytes) of the current
position. This means that ‘n’ bytes have already read.
Example : rewind(fp);
n = ftell ( fp);
n = ftell ( fp);
Rewind function
 The Rewind function takes a file pointer and resets the
position to the start of the (in bytes) file. The statement is
 It will assign ‘o’ to n’ because the file position has been set to
the start of the file by rewind.
 The first byte in the file is numbered as ‘0’ second as ‘1’ and
so on.
 This function help us in reading a file more than once, without
having to close and open file.
Rewind (fp);
N = ftell(fp);
Fseek function
 Fseek function is used to move the file position to a desired
location within the file. It takes the following form
Syntax:
 Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or
variable of type ‘long’, and position is an integer variable. The
offset specifies the positions (bytes) to be moved from the
location specified by position.
Fseek (file pointer, offset, position);
Value Meaning
0 Beginning of the file
1 Current position
2 End of the file
 The Offset may be ‘+’ve meaning moved forwards, or ‘-
‘ ve meaning moved backwards.
Example:
Example:
Fseek(fp,oL,0) goto beginning
Fseek(fp,m,0) move (n+1)th byte in the file
Fseek (fp,m,1) goto forward by ‘m’ bytes
Fseek (fp,-m,1) goto backward by ‘m’ bytes from the current position
Fseek (fp ,-m,2) goto backward by ‘m’ bytes from the end
program
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%ct",ch);
}
}
fclose(fp);
getch();
}
Command line arguments
 It is parameter supplied to a program when the program is
invoked.
 This parameter may represent a file name the program
should process.
 It is possible to pass some values from the command line to
your C programs when they are executed. These values are
called command line arguments.
 Many times they are important for your program especially
when you want to control your program from outside instead of
hard coding those values inside the code.
The command line arguments are handled using main()
function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which
points to each argument passed to the program.
Syntax:
main(int argc, char *argv[])
{
………….
………….
}
Program for command line arguments
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %sn", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.n");
}
else
{
printf("One argument expected.n");
}
}
$./a.out testing
The argument supplied is testing.
$./a.out testing1 testing2
Too many arguments supplied.
Single argument
Twoargument
File management

More Related Content

What's hot (20)

PHP HTML CSS Notes
PHP HTML CSS  NotesPHP HTML CSS  Notes
PHP HTML CSS Notes
 
Learn C
Learn CLearn C
Learn C
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Enums in c
Enums in cEnums in c
Enums in c
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Function in c
Function in cFunction in c
Function in c
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
C pointer
C pointerC pointer
C pointer
 
Python file handling
Python file handlingPython file handling
Python file handling
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
Css
CssCss
Css
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
File in C language
File in C languageFile in C language
File in C language
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Functions in C
Functions in CFunctions in C
Functions in C
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 

Similar to File management (20)

File in c
File in cFile in c
File in c
 
File handling-c
File handling-cFile handling-c
File handling-c
 
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
 
Unit5
Unit5Unit5
Unit5
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Unit 8
Unit 8Unit 8
Unit 8
 
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
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File handling C program
File handling C programFile handling C program
File handling C program
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Handout#01
Handout#01Handout#01
Handout#01
 

More from lalithambiga kamaraj (20)

Firewall in Network Security
Firewall in Network SecurityFirewall in Network Security
Firewall in Network Security
 
Data Compression in Multimedia
Data Compression in MultimediaData Compression in Multimedia
Data Compression in Multimedia
 
Data CompressionMultimedia
Data CompressionMultimediaData CompressionMultimedia
Data CompressionMultimedia
 
Digital Audio in Multimedia
Digital Audio in MultimediaDigital Audio in Multimedia
Digital Audio in Multimedia
 
Network Security: Physical security
Network Security: Physical security Network Security: Physical security
Network Security: Physical security
 
Graphs in Data Structure
Graphs in Data StructureGraphs in Data Structure
Graphs in Data Structure
 
Package in Java
Package in JavaPackage in Java
Package in Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Data structure
Data structureData structure
Data structure
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Digital Image Processing
Digital Image ProcessingDigital Image Processing
Digital Image Processing
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costs
 
Datamining
DataminingDatamining
Datamining
 
Digital Components
Digital ComponentsDigital Components
Digital Components
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
Io management disk scheduling algorithm
Io management disk scheduling algorithmIo management disk scheduling algorithm
Io management disk scheduling algorithm
 
Recovery system
Recovery systemRecovery system
Recovery system
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Inheritance
InheritanceInheritance
Inheritance
 
Managing console of I/o operations & working with files
Managing console of I/o operations & working with filesManaging console of I/o operations & working with files
Managing console of I/o operations & working with files
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 

Recently uploaded (20)

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

File management

  • 2. File management Introduction Defining and Opening a File Closing a File Input/output operations on File Error Handling During I/O Operation Random Access to Files Command Line Arguments
  • 3. Introduction  A file represents a sequence of bytes on the disk where a group of related data is stored.  File is created for permanent storage of data. It is a ready made structure.  Real life problems involve large volume of data and in such cases, the console oriented I/O operations pose two major problems It becomes cumbersome and time consuming to handle large volumes of data through terminals. The entire data is lost when either the program is terminated or computer is turned off .
  • 4. Basic File operations .They are, 1. Naming a file 2. Opening a file 3. Reading from a file 4. Writing data into a file 5. Closing a file There are two distinct ways to perform file operations in c. The first one is known as the low-level I/O and used UNIX system calls. The second method is know n as the high-level I/O operation and uses function in C’s standard I/O library It is used for store a data permanently in computer. Using this concept we can store our data in Secondary memory (Hard disk).
  • 5. High level I/O function S.No Function Name Operation 1 fopen() Creates a new file for use Opens a new existing file for use 2 fclose() Closes a file which has been opened for use 3 getc() Reads a character from a file 4 putc() Writes a character to a file 5 fprintf() Writes a set of data values to a file 6 fscanf() Reads a set of data values from a file 7 getw() Reads a integer from a file 8 putw() Writes an integer to the file 9 fseek() Sets the position to a desired point in the file 10 ftell() Gives the current position in the file 11 rewind() Sets the position to the beginning of the file
  • 6. Defining AND OPENING file • To store data in a file in the secondary memory specify certain things about the file to the operating system. They include , • Filename is a string of characters that makeup a valid for the operating system. • Data structure of a file is defined as ‘File’ in the library of standard I/O function definition . • File is a defined data type. • It contains two parts, a Primary name and optional period with extension. 1.File name 2.Data structure 3. Purpose Example: Input .data PROG.C
  • 7. File operations  Fopen function: The general format for declaring and opening a file is  The variable fp has a pointer to the data type File opens the File name and pointer assigns an identifier to the File type pointer fp.  This pointer which contains all the information about the File subsequently used as a communication link between the system and the program. Mode can be one the following  r - open the file for reading only.  w - open the file writing only.  a - open the file for appending (adding) data to each. FILE *fp; Fp = fopen ( “file name”, “mode” );
  • 8. File opening with example  Both ‘file name’ and ‘mode’ are specified as string they should be enclosed in double quotation marks (“ ”). Example: Where fp1,fp2 are pointer  The ‘fp1’ is opens the File named as data for reading mode only.  Then ‘fp2’ is opens the File named as result for writing mode only. FILE * fp1, *fp2; Fp1 = fopen (“data’’, “r”); Fp2= fopen (“result”, “w”);
  • 9. Program for file opening Reading #include<stdio.h> void main() { FILE *fopen(), *fp; int c; fp = fopen("prog.c","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); } Writing #include <stdio.h> int main() { FILE *fp; file = fopen("file.txt","w"); /*Create a file and add text*/ fprintf(fp,"%s",” example :"); /*writes data to the file*/ fclose(fp); /*done!*/ return 0; } Appending #include <stdio.h> int main() { FILE *fp ; file = fopen("file.txt","a"); fprintf(fp,"%s"," example :"); /*append some text*/ fclose(fp); return 0; }
  • 10. Additional modes of operation a opens a text file in append mode r+ opens a text file in both reading and writing mode w+ opens a text file in both reading and writing mode a+ opens a text file in both reading and writing mode rb opens a binary file in reading mode wb opens or create a binary file in writing mode ab opens a binary file in append mode rb+ opens a binary file in both reading and writing mode wb+ opens a binary file in both reading and writing mode ab+ opens a binary file in both reading and writing mode
  • 11. Closing a file  A File must be closed after all operations have been completed. The general form of fclose function is Syntax: Example: :  This program opens two files and closes them after all operations on them are completed once a file is closed its file pointer can be reused for another file. Fclose (file pointer); Fp1 =fopen (“input”, "W”); Fp2 = fopen(“output”, “r”); ………. ………. Fclose(fp1); Fclose(fp2); ……….
  • 12. Program for closing a file #include <stdio.h> main( ) { FILE *fp; char c; funny = fopen("TENLINES.TXT", "r"); if (fp == NULL) printf("File doesn't existn"); else { do { c = getc(fp); /* get one character from the file */ putchar(c); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF (end of file) */ } fclose(fp); }
  • 13. getc function The getc is used to read a character from a file that has been opened in read mode. Syntax: The read a character from the file whose pointer is file pointer and assigned the reading character to ‘C’. The reading is terminated when getc encounter end of file mark EOF. Example : File *fp; Char c; …………. Fp=fopen (“input”, “r”); While(c=getc(fp)!=Eof) Putchar ( c ); C=getc (file pointer); Input/output operations on files
  • 14. putcfunction  The putc is used to write a character to a file that has been opened in write mode. Syntax:  The read a character through to the variable and put these character through whose file pointer is fp.  The writing is terminated when putc encounters the end of file mark EOF. Example: Putc (c,fp); FILE *fp; Char C; ……….. Fp=fopen(“input”, “w”); While (c = getchar( c )!= EOF) Putc(c, fp);
  • 15. getw function  The simplest integer oriented file I/o function is getw that has been opened in read mode . Syntax:  Where read an integer value from the file whose file pointer is fp and assigned the reading numbers to num.  The reading is terminated when getw encounters the end of file mark EOF. Example : Num =getw (fp); FILE *fp Int num; ………. Fp=fopen (“input”, "r”); While (num=getw(fp)!=EOF) Printf(“%d”, num);
  • 16. Putw function  The simplest I/O integer oriented function is putw is used to create an integer value to a file that has been opened in write mode. Syntax:  The read a number through to the variable ‘num’ and put the number into the file whose file pointer is fp.  The waiting is terminted when ‘Putw’ encounters the end of file mark Eof (i.e,num=0) Example : FILE *fp Int num; Fp=fopen (“INPUT”, "w”); Scanf(“%d”, & num); While (num!= fp) Putw(num,fp); Scanf(“%d”, & num); Putw(num,fp);
  • 17. fprintf function  The fprintf statement is used to write data items to the file whose file pointer is opened in the writing mode.  ‘fprintf’ perform I/O operations an files. Syntax:  Where ‘fp’ is a file pointer associated with a file that has been opened for writing.  The control string contains output specifications for the items in the list.  The list may be including variable constants and strings. Example :  Where ‘name is an array variable of type and age is an int variable. fprintf (fp1, "%s %d %f”, name age,7.5); Fprintf (fp, "control string", list);
  • 18. fscanffunction  The fscanf function is used to read data items to the file whose pointer is opened in the reading mode.  fscanf function performs I/O operations on files. Syntax:  This statement reading of the items in the list from the file specified by fp. The control string contains input specifications for the items in the list. Example :  Where “item” is an array variable of type and quantity is an int variable.  fscanf returns the no. of items when the end of file is reached 'i' returns the value EOF. fscanf (fp1, “%s %d”, item & quantity); fscanf (fp, “control string”, list);
  • 19. #include <stdio.h> int main () { char name [20]; int age, length; FILE *fp; fp = fopen ("test.txt","w"); fprintf (fp, "%s %d", “Fresh2refresh”, 5); length = ftell(fp); // Cursor position is now at the end of file /* You can use fseek(fp, 0, SEEK_END); also to move the cursor to the end of the file */ rewind (fp); // It will move cursor position to the beginning of the file fscanf (fp, "%d", &age); fscanf (fp, "%s", name); fclose (fp); printf ("Name: %s n Age: %d n",name,age); printf ("Total number of characters in file is %d", length); return 0; } OUTPUT: Name: Fresh2refresh Age: 5 Total number of characters in file is 15 Program for printf and scanf
  • 20. Error handling during i/o operations  It is possible that an error may occur during I/O operations on a file. Typical error situations include: 1. Trying to read beyond the end-of-file mark. 2. Device overflow. 3. Trying to use a file that has not been opened. 4. Trying to perform an operation on a file, when the file is opened for another type of operation. 5. Opening a file with an invalid filename. 6. Attempting to write to a write-protected file.
  • 21. feof function  The feof function can be used to test for an end of file condition .  It takes a file pointer as an argument and returns a non-zero integer value id all of the data from the specified file has been read and returns zero otherwise. Example:  This statement gives the end of data when encountered end of file condition. If (feof (fp) Printf(“end of file”);
  • 22. ferror function  The ferror function is also takes a file pointer its argument and returns a non-zero integer.  If an error has been detected up to that point during processing it returns zero otherwise. Example :  Print the error message if the reading is not successful. If (ferror (fp)!=0) Printf(“file could not be open”);
  • 23. Program for ferror function #include <stdio.h> int main() { FILE *fp; char c; fp = fopen("file.txt", "w"); c = fgetc(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txtn"); } clearerr(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txtn"); } fclose(fp); return(0); } Output: Error in reading from file : file.txt
  • 24. Random access to files  This file functions are useful to reading and writing data sequentially.  When we are interested in accessing only a particular part of a file and not in reading the other parts.  This can be achieved with the help of the functions fseek, ftell and rewind available in the I/O library.
  • 25. ftell function  The ftell function is useful in saving the current position of a file, which can be used later in the program .  It takes the following form Syntax:  Where ‘n’ gives the relative offset (in bytes) of the current position. This means that ‘n’ bytes have already read. Example : rewind(fp); n = ftell ( fp); n = ftell ( fp);
  • 26. Rewind function  The Rewind function takes a file pointer and resets the position to the start of the (in bytes) file. The statement is  It will assign ‘o’ to n’ because the file position has been set to the start of the file by rewind.  The first byte in the file is numbered as ‘0’ second as ‘1’ and so on.  This function help us in reading a file more than once, without having to close and open file. Rewind (fp); N = ftell(fp);
  • 27. Fseek function  Fseek function is used to move the file position to a desired location within the file. It takes the following form Syntax:  Here ‘file pointer’ is a pointer to the file, ‘offset’ is a number or variable of type ‘long’, and position is an integer variable. The offset specifies the positions (bytes) to be moved from the location specified by position. Fseek (file pointer, offset, position); Value Meaning 0 Beginning of the file 1 Current position 2 End of the file
  • 28.  The Offset may be ‘+’ve meaning moved forwards, or ‘- ‘ ve meaning moved backwards. Example: Example: Fseek(fp,oL,0) goto beginning Fseek(fp,m,0) move (n+1)th byte in the file Fseek (fp,m,1) goto forward by ‘m’ bytes Fseek (fp,-m,1) goto backward by ‘m’ bytes from the current position Fseek (fp ,-m,2) goto backward by ‘m’ bytes from the end
  • 29. program #include<stdio.h> #include<conio.h> void main() { FILE *fp; char ch; clrscr(); fp=fopen("file1.c", "r"); if(fp==NULL) printf("file cannot be opened"); else { printf("Enter value of n to read last ‘n’ characters"); scanf("%d",&n); fseek(fp,-n,2); while((ch=fgetc(fp))!=EOF) { printf("%ct",ch); } } fclose(fp); getch(); }
  • 30. Command line arguments  It is parameter supplied to a program when the program is invoked.  This parameter may represent a file name the program should process.  It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments.  Many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
  • 31. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Syntax: main(int argc, char *argv[]) { …………. …………. }
  • 32. Program for command line arguments #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %sn", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.n"); } else { printf("One argument expected.n"); } } $./a.out testing The argument supplied is testing. $./a.out testing1 testing2 Too many arguments supplied. Single argument Twoargument