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 Guide: Opening, Reading, Writing and Closing Files in C

More Related Content

What's hot (20)

C string
C stringC string
C string
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
C functions
C functionsC functions
C functions
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Strings
StringsStrings
Strings
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Singly Linked List & Data Structure
Singly Linked List & Data StructureSingly Linked List & Data Structure
Singly Linked List & Data Structure
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Operation on string presentation
Operation on string presentationOperation on string presentation
Operation on string presentation
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
Structure in C
Structure in CStructure in C
Structure in C
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
String in c programming
String in c programmingString in c programming
String in c programming
 
Object Oriented Programming Languages
Object Oriented Programming LanguagesObject Oriented Programming Languages
Object Oriented Programming Languages
 
Array in c
Array in cArray in c
Array in c
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
C++ string
C++ stringC++ string
C++ string
 
File Management in C
File Management in CFile Management in C
File Management in C
 

Similar to File Management Guide: Opening, Reading, Writing and Closing Files in C

Similar to File Management Guide: Opening, Reading, Writing and Closing Files in C (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
 
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
 
File handling in c
File handling in cFile handling in c
File handling in c
 
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
 
Handout#01
Handout#01Handout#01
Handout#01
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 

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

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

File Management Guide: Opening, Reading, Writing and Closing Files in C

  • 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