SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 

Tendances (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
 

En vedette (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
 

Similaire à 1file handling

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
ssuserad38541
 
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
Rajeshkumar Reddy
 

Similaire à 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
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
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
 
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
AnaAcapella
 

Dernier (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
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
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
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
 
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...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
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
 
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
 
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...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
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...
 

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(); }