SlideShare a Scribd company logo
1 of 20
File Management in C
What is a File?

• A file is a collection of related data that a
computers treats as a single unit.
• Computers store files to secondary storage so
that the contents of files remain permanently
when a computer shuts down.
• When a computer reads a file, it copies the
file from the storage device to memory;
when it writes to a file, it transfers data from
memory to the storage device.
Files
• File – place on disc where group of related data is
stored
– E.g. your C programs, executables

• Basic file operations
–
–
–
–
–

Naming
Opening
Reading
Writing
Closing
Filename
• String of characters that make up a valid filename for OS

• May contain two parts
– Primary
– Optional period with extension

• Examples: a.out, prog.c, temp, text.out
General format for opening file
FILE *fp; /*variable fp is pointer to type FILE*/

fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */

• fp
– contains all information about file
– Communication link between system and program

• Mode can be
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data
Different modes
• Writing mode
– if file already exists then contents are deleted,
– else new file with specified name created

• Appending mode
– if file already exists then file opened with contents safe
– else new file created

• Reading mode
– if file already exists then opened with contents safe
– else error occurs.
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
More on File Open Modes
Additional modes
• r+ (read+write) open to beginning for both
reading/writing
• In this mode the previous record of file is not deleted
• w+ (write+read) same as w, we can also read record
which is stored in the file
• a+ (append+read) same as ‘a’, we can also read
record which is stored in the file
Closing a file
• File must be closed as soon as all operations on it
completed
• Ensures
– All outstanding information associated with file flushed
out from buffers
– All links to file broken
– Accidental misuse of file prevented

• If want to change mode of file, then first close and
open again
Closing a file
Syntax: fclose(file_pointer);

Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);

• pointer can be reused after closing
Input/Output operations on files
• C provides several different functions for
reading/writing
•
•
•
•
•
•

getc() – read a character from the file
putc() – write a character into the file
getw() – read integer from the file
putw() – write integer into the file
fprintf() – write set of data values into the file
fscanf() – read set of data values from the file
getc() and putc()
• handle one character at a time like getchar() and
putchar()
• syntax: putc(c,fp1);
– c : a character variable
– fp1 : pointer to file opened with mode w

• syntax: c = getc(fp2);
– c : a character variable
– fp2 : pointer to file opened with mode r

• file pointer moves by one character position after every
getc() and putc()
• getc() returns end-of-file marker EOF when file end
reached
Program to read/write using getc/putc
#include <stdio.h>
main()
{ FILE *f1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
while((c=getchar()) != ‘*’) /*get char from keyboard until ‘*’ */
putc(c,f1);
/*write a character to INPUT */
fclose(f1);
f1=fopen(“INPUT”, “r”);

/* close INPUT */
/* reopen file */

while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(“%c”, c);
/* print character to screen */
fclose(f1);
} /*end main */
getw() and putw()
• handle one integer at a time
• syntax: putw(i,fp1);
– i : an integer variable
– fp1 : pointer to file ipened with mode w

• syntax: i = getw(fp2);
– i : an integer variable
– fp2 : pointer to file opened with mode r

• file pointer moves by one integer position
• getw() returns end-of-file marker EOF when file end reached
C program using getw, putw,fscanf, fprintf
#include <stdio.h>
main()
{ int i,sum1=0;
FILE *f1;
/* open files */
f1 = fopen("int_data.bin","w");
/* write integers to files in binary
and text format*/
for(i=10;i<15;i++)
putw(i,f1);
fclose(f1);
f1 = fopen("int_data.bin","r");
while((i=getw(f1))!=EOF)
{ sum1+=i;
printf("binary file: i=%dn",i);
} /* end while getw */
printf("binary sum=%d,sum1);
fclose(f1);
}

#include <stdio.h>
main()
{ int i, sum2=0;
FILE *f2;
/* open files */
f2 = fopen("int_data.txt","w");
/* write integers to files in binary
and text format*/
for(i=10;i<15;i++) printf(f2,"%dn",i);
fclose(f2);
f2 = fopen("int_data.txt","r");
while(fscanf(f2,"%d",&i)!=EOF)
{ sum2+=i; printf("text file:
i=%dn",i);
} /*end while fscanf*/
printf("text sum=%dn",sum2);
fclose(f2);
}
On execution of previous Programs
$ ./a.out
binary file: i=10
binary file: i=11
binary file: i=12
binary file: i=13
binary file: i=14
binary sum=60,
$ cat int_data.txt
10
11
12
13
14

$ ./a.out
text file: i=10
text file: i=11
text file: i=12
text file: i=13
text file: i=14
text sum=60
$ more int_data.bin
^@^@^@^K^@^@^@^L^@^@^@^
M^@^@^@^N^@^@^@
$
fscanf() and fprintf()
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %fn”, i, f);
fprintf(stdout, “%f n”, f); /*note: stdout refers to screen */
fscanf(f2, “%d %f”, &i, &f);

• fscanf returns EOF when end-of-file reached
Random access to files
• how to jump to a given position (byte number) in a file
without reading all the previous data?
• fseek (file-pointer, offset, position);
• position: 0 (beginning), 1 (current), 2 (end)
• offset: number of locations to move from position
Example: fseek(fp,-m, 1); /* move back by m bytes from current
position */
fseek(fp,m,0); /* move to (m+1)th byte in file */
fseek(fp, -10, 2); /* what is this? */

• ftell(fp) returns current byte position in file
• rewind(fp) resets position to start of file
Random access to files
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("check.txt","w");
while((c=getchar())!='*')
{
putc(c,fp);
}
printf("n position of file pointer %d",ftell(fp));
rewind(fp);
printf("n position of file pointer %d",ftell(fp));
fclose(fp);
fp=fopen("check.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
fseek(fp,2,1);
}
getch();
}
1file handling

More Related Content

What's hot (20)

File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File Management in C
File Management in CFile Management in C
File Management 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
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File handling in c
File handling in c File handling in c
File handling in c
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File_Management_in_C
File_Management_in_CFile_Management_in_C
File_Management_in_C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
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
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Viewers also liked (16)

праздничный пирогT
праздничный пирогTпраздничный пирогT
праздничный пирогT
 
Union
UnionUnion
Union
 
Recursion prog
Recursion progRecursion prog
Recursion prog
 
Structure
StructureStructure
Structure
 
письма с фронта.Pptx3
письма с фронта.Pptx3письма с фронта.Pptx3
письма с фронта.Pptx3
 
C programming language
C programming languageC programming language
C programming language
 
Recursion prog (1)
Recursion prog (1)Recursion prog (1)
Recursion prog (1)
 
прикл. винни пуха
прикл. винни пухаприкл. винни пуха
прикл. винни пуха
 
5bit field
5bit field5bit field
5bit field
 
6 enumerated, typedef
6 enumerated, typedef6 enumerated, typedef
6 enumerated, typedef
 
Pointers
PointersPointers
Pointers
 
4 dynamic memory allocation
4 dynamic memory allocation4 dynamic memory allocation
4 dynamic memory allocation
 
Class Bivalvia Notes
Class Bivalvia NotesClass Bivalvia Notes
Class Bivalvia Notes
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Type conversion
Type conversionType conversion
Type conversion
 
Data type
Data typeData type
Data type
 

Similar to 1file handling

File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for BeginnersVSKAMCSPSGCT
 
Engineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptxEngineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptxhappycocoman
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptC-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptssuserad38541
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.pptyuvrajkeshri
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptxLECO9
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptxSKUP1
 
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.pdfsudhakargeruganti
 
C-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxC-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxbanu236831
 
File management
File managementFile management
File managementsumathiv9
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
Files in c
Files in cFiles in c
Files in cTanujaA3
 

Similar to 1file handling (20)

Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
File Handling in C Programming for Beginners
File Handling in C Programming for BeginnersFile Handling in C Programming for Beginners
File Handling in C Programming for Beginners
 
Engineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptxEngineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptx
 
C-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.pptC-Programming Chapter 5 File-handling-C.ppt
C-Programming Chapter 5 File-handling-C.ppt
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptx
 
C-Programming File-handling-C.pptx
C-Programming  File-handling-C.pptxC-Programming  File-handling-C.pptx
C-Programming File-handling-C.pptx
 
File management
File managementFile management
File management
 
Unit5
Unit5Unit5
Unit5
 
6. chapter v
6. chapter v6. chapter v
6. chapter v
 
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
 
Unit 8
Unit 8Unit 8
Unit 8
 
C-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptxC-FILE MANAGEMENT.pptx
C-FILE MANAGEMENT.pptx
 
finally.c.ppt
finally.c.pptfinally.c.ppt
finally.c.ppt
 
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
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Files in c
Files in cFiles in c
Files in c
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

1file handling

  • 2. What is a File? • A file is a collection of related data that a computers treats as a single unit. • Computers store files to secondary storage so that the contents of files remain permanently when a computer shuts down. • When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device.
  • 3. Files • File – place on disc where group of related data is stored – E.g. your C programs, executables • Basic file operations – – – – – Naming Opening Reading Writing Closing
  • 4. Filename • String of characters that make up a valid filename for OS • May contain two parts – Primary – Optional period with extension • Examples: a.out, prog.c, temp, text.out
  • 5. General format for opening file FILE *fp; /*variable fp is pointer to type FILE*/ fp = fopen(“filename”, “mode”); /*opens file with name filename , assigns identifier to fp */ • fp – contains all information about file – Communication link between system and program • Mode can be – r open file for reading only – w open file for writing only – a open file for appending (adding) data
  • 6. Different modes • Writing mode – if file already exists then contents are deleted, – else new file with specified name created • Appending mode – if file already exists then file opened with contents safe – else new file created • Reading mode – if file already exists then opened with contents safe – else error occurs. FILE *p1, *p2; p1 = fopen(“data”,”r”); p2= fopen(“results”, w”);
  • 7. More on File Open Modes
  • 8. Additional modes • r+ (read+write) open to beginning for both reading/writing • In this mode the previous record of file is not deleted • w+ (write+read) same as w, we can also read record which is stored in the file • a+ (append+read) same as ‘a’, we can also read record which is stored in the file
  • 9. Closing a file • File must be closed as soon as all operations on it completed • Ensures – All outstanding information associated with file flushed out from buffers – All links to file broken – Accidental misuse of file prevented • If want to change mode of file, then first close and open again
  • 10. Closing a file Syntax: fclose(file_pointer); Example: FILE *p1, *p2; p1 = fopen(“INPUT.txt”, “r”); p2 =fopen(“OUTPUT.txt”, “w”); …….. …….. fclose(p1); fclose(p2); • pointer can be reused after closing
  • 11. Input/Output operations on files • C provides several different functions for reading/writing • • • • • • getc() – read a character from the file putc() – write a character into the file getw() – read integer from the file putw() – write integer into the file fprintf() – write set of data values into the file fscanf() – read set of data values from the file
  • 12. getc() and putc() • handle one character at a time like getchar() and putchar() • syntax: putc(c,fp1); – c : a character variable – fp1 : pointer to file opened with mode w • syntax: c = getc(fp2); – c : a character variable – fp2 : pointer to file opened with mode r • file pointer moves by one character position after every getc() and putc() • getc() returns end-of-file marker EOF when file end reached
  • 13. Program to read/write using getc/putc #include <stdio.h> main() { FILE *f1; char c; f1= fopen(“INPUT”, “w”); /* open file for writing */ while((c=getchar()) != ‘*’) /*get char from keyboard until ‘*’ */ putc(c,f1); /*write a character to INPUT */ fclose(f1); f1=fopen(“INPUT”, “r”); /* close INPUT */ /* reopen file */ while((c=getc(f1))!=EOF) /*read character from file INPUT*/ printf(“%c”, c); /* print character to screen */ fclose(f1); } /*end main */
  • 14. getw() and putw() • handle one integer at a time • syntax: putw(i,fp1); – i : an integer variable – fp1 : pointer to file ipened with mode w • syntax: i = getw(fp2); – i : an integer variable – fp2 : pointer to file opened with mode r • file pointer moves by one integer position • getw() returns end-of-file marker EOF when file end reached
  • 15. C program using getw, putw,fscanf, fprintf #include <stdio.h> main() { int i,sum1=0; FILE *f1; /* open files */ f1 = fopen("int_data.bin","w"); /* write integers to files in binary and text format*/ for(i=10;i<15;i++) putw(i,f1); fclose(f1); f1 = fopen("int_data.bin","r"); while((i=getw(f1))!=EOF) { sum1+=i; printf("binary file: i=%dn",i); } /* end while getw */ printf("binary sum=%d,sum1); fclose(f1); } #include <stdio.h> main() { int i, sum2=0; FILE *f2; /* open files */ f2 = fopen("int_data.txt","w"); /* write integers to files in binary and text format*/ for(i=10;i<15;i++) printf(f2,"%dn",i); fclose(f2); f2 = fopen("int_data.txt","r"); while(fscanf(f2,"%d",&i)!=EOF) { sum2+=i; printf("text file: i=%dn",i); } /*end while fscanf*/ printf("text sum=%dn",sum2); fclose(f2); }
  • 16. On execution of previous Programs $ ./a.out binary file: i=10 binary file: i=11 binary file: i=12 binary file: i=13 binary file: i=14 binary sum=60, $ cat int_data.txt 10 11 12 13 14 $ ./a.out text file: i=10 text file: i=11 text file: i=12 text file: i=13 text file: i=14 text sum=60 $ more int_data.bin ^@^@^@^K^@^@^@^L^@^@^@^ M^@^@^@^N^@^@^@ $
  • 17. fscanf() and fprintf() • similar to scanf() and printf() • in addition provide file-pointer • given the following – file-pointer f1 (points to file opened in write mode) – file-pointer f2 (points to file opened in read mode) – integer variable i – float variable f • Example: fprintf(f1, “%d %fn”, i, f); fprintf(stdout, “%f n”, f); /*note: stdout refers to screen */ fscanf(f2, “%d %f”, &i, &f); • fscanf returns EOF when end-of-file reached
  • 18. Random access to files • how to jump to a given position (byte number) in a file without reading all the previous data? • fseek (file-pointer, offset, position); • position: 0 (beginning), 1 (current), 2 (end) • offset: number of locations to move from position Example: fseek(fp,-m, 1); /* move back by m bytes from current position */ fseek(fp,m,0); /* move to (m+1)th byte in file */ fseek(fp, -10, 2); /* what is this? */ • ftell(fp) returns current byte position in file • rewind(fp) resets position to start of file
  • 19. Random access to files • • • • • • • • • • • • • • • • • • • • • • main() { FILE *fp; char c; clrscr(); fp=fopen("check.txt","w"); while((c=getchar())!='*') { putc(c,fp); } printf("n position of file pointer %d",ftell(fp)); rewind(fp); printf("n position of file pointer %d",ftell(fp)); fclose(fp); fp=fopen("check.txt","r"); while((c=getc(fp))!=EOF) { printf("%c",c); fseek(fp,2,1); } getch(); }