SlideShare a Scribd company logo
1 of 36
Download to read offline
File I/O
2
File Input/Output
 Input/Output device for programs
– Input: Keyboard
– Output: Monitor
 Is it possible to read or write data from/to files?
A B C
1 80 90 70
2 80 60 40
3 60 50 70
…
C program
A B C Avg.
1 80 90 70 80
2 80 60 40 60
3 60 50 70 60
…
read write
file1.txt file2.txt
3
File Input/Ooutput
 File Input/Output Process
Open the file
Read data from file
Write data to file
Close the file
fopen
fscanf, fprintf, fgets, fputs, …
fclose
4
File Operation Function fopen()
 fopen()
– Used to prepare external files to use in programs
• All files are associated with a data structure known as a stream
if fopen successes
– Return value: a pointer of FILE structure
• File stream is manipulated with FILE pointer returned by fopen
 fopen() Syntax
FILE *fopen( const char *filename, const char *mode );
Return by file pointer Filename in disk File open mode
5
File Operation Function fopen()
 Example
– Open my_file.txt in the read mode
– Return NULL at failure
– Eg) If a file named “my_file.txt” does not exist
FILE *fp ;
fp = fopen(“my_file.txt”, “r”);
6
File Operation Function fopen()
 Example
– Open my_file.txt in the write mode
– If my_file.txt does not exist, it is created
– If my_file.txt exists, the content of the file is erased
FILE *fp ;
fp = fopen(“my_file.txt”, “w”);
7
File Operation Function fopen()
 Example
– Open my_file.txt in the append mode (similar to write mode)
– If my_file.txt does not exist, it is created
– If my_file.txt exists, the file content is kept and new data is
appended at the end of file
FILE *fp ;
fp = fopen(“my_file.txt”, “a”);
8
File Operation Function fopen()
 Example
– Open my_file.txt in the read/write mode
– Return NULL, if my_file.txt does not exist
– If my_file.txt exists, the file content is kept
– Read/write pointer is positioned at the beginning of the file
FILE *fp ;
fp = fopen(“my_file.txt”, “r+”);
9
File Operation Function fopen()
 Example
– Open my_file.txt in the read/write mode
– If my_file.txt does not exist, it is created
– If my_file.txt exists, the file content is erased
FILE *fp ;
fp = fopen(“my_file.txt”, “w+”);
10
File Operation Function fopen()
 Example
– Open my_file.txt in the read/write mode
– If my_file.txt does not exist, it is created
– If my_file.txt exists, the file content is kept
– Read/write pointer is positioned at the end of the file
FILE *fp ;
fp = fopen(“my_file.txt”, “a+”);
11
File pointer
 File pointer
– File I/O is processed through file pointer
 ‘FILE’ Type
 a type of structure defined with typedef in stdio.h contains
information of file
[Ex]
FILE *fp; /* declare ‘fp’ as
file pointer */
12
File Operation Function fclose()
 fclose()
– Close the file opened by fopen
 fclose() Syntax
int fclose( FILE *stream );
file pointer returned by fopen
Returns 0 : successful
EOF : error
(EOF is defined as –1 in stdio.h)
13
File Operation Function fopen()
 fclose() Example
#include <stdio.h>
void main() {
FILE *fp ;
fp = fopen(“my_file.txt”, “r”);
...
fclose( fp ) ;
}
14
Formatted I/O Function fprintf()
 fprintf()
– printf() for file operation
– First argument is the file pointer which has one of write
modes (w, a, r+, w+, a+)
– The rest arguments are the same as printf()
– fprintf() writes data into abc.txt
FILE* fp = fopen( “abc.txt”, “w” ) ;
fprintf( fp, “%d %dn”, 1, 2 );
15
Formatted I/O Function fprintf()
 fscanf()
– scanf() for file operation
– First argument is file pointer which has one of read modes
(r, r+, w+, a+)
– The rest arguments are the same as printf()
– scanf() reads data from abc.txt
int i, j ;
FILE* fp = fopen( “abc.txt”, “r” ) ;
fscanf( fp, “%d %d”, &i, &j );
16
feof() Function
 feof()
– Check whether the file pointer is at the end of file or not
int feof( FILE *stream );
Opened file pointer
Returns none-zero : if it is EOF
0 : if it is not EOF
17
Formatted I/O Function fprintf() and fscanf()
#include <stdio.h>
void main() {
int i, j, k ;
FILE *ifp, *ofp ;
ifp = fopen("abc.txt", "r" ) ;
ofp = fopen("cal.txt", "w" ) ;
fscanf( ifp, "%d %d %d", &i, &j, &k ) ;
fprintf( ofp, "sum: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
}
 fprintf(), fscanf() Example
1 2 3
abc.txt
cal.txt is not exist
18
Formatted I/O Function fprintf() and
fscanf()
#include <stdio.h>
void main() {
int i, j, k ;
FILE *ifp, *ofp ;
ifp = fopen("abc.txt", "r" ) ;
ofp = fopen("cal.txt", "w" ) ;
fscanf( ifp, "%d %d %d", &i, &j, &k ) ;
fprintf( ofp, "sum: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
}
 fprintf(), fscanf() Example
1 2 3
abc.txt
sum: 6
cal.txt
19
Formatted I/O Function fprintf() and
fscanf()
#include <stdio.h>
void main() {
int i, j, k ;
FILE *ifp, *ofp ;
ifp = fopen("abc.txt", "r" ) ;
ofp = fopen("cal.txt", "a" ) ;
fscanf( ifp, "%d %d %d", &i, &j, &k ) ;
fprintf( ofp, "sum: %dn", i + j + k ) ;
fclose( ifp ) ;
fclose( ofp ) ;
}
 fprintf(), fscanf() Example
1 2 3
abc.txt
sum: 6
cal.txt
20
Formatted I/O Function fprintf() and
fscanf()
#include <stdio.h>
void main() {
char c ;
FILE *ifp, *ofp ;
ifp = fopen("abc.txt", "r" ) ;
ofp = fopen("abc2.txt", "a" ) ;
while( feof(ifp) == 0 ) {
fscanf( ifp, "%c", &c ) ;
fprintf( ofp, "%c", c ) ;
}
fclose( ifp ) ;
fclose( ofp ) ;
}
 fprintf(), fscanf() Example
This is a
file.
1 2 3
abc.txt
This is a
file.
1 2 3
abc2.txt
21
Misc. File I/O Functions
 fgetc() , getc()
– Read a character from a file
• If there is no more character to read, return EOF
– fgetc() is equivalent to getc()
char c ;
FILE *fp = fopen("abc.txt", "r" ) ;
while( (c = fgetc(fp)) != EOF )
printf("%c", c ) ;
int fgetc ( FILE *stream ) ;
22
Misc. File I/O Functions
 fputc() , putc()
– Write a character to a file
– fputc() is identical to putc()
char c ;
FILE *fp = fopen("abc.txt", "r" ) ;
FILE *ofp = fopen("xyz.txt", "w" ) ;
while( (c = fgetc(fp)) != EOF )
fputc( c, ofp ) ;
int fputc ( int c, FILE *stream ) ;
23
Misc. File I/O Functions
 fputs() : Writing a string
– puts() for file I/O
– Print a string into file
– At success, it returns a non-negative value
– At failure, it returns EOF
int fputs(char *str, FILE *fp);
24
Misc. File I/O Functions
FILE *fp;
int i;
char *data[3]={"to ben","or notn","to ben"};
fp = fopen("abc.txt", "w");
for(i = 0; i<3; i++) fputs(data[i],fp);
fclose( fp );
25
Misc. File I/O Functions
 fgets() : Reading a String
– gets() for file I/O
– Read (num -1) characters from fp and store to str
– When fp meets ‘n’ or EOF, it stops reading and store NULL
into str
– At success, it returns the address of str. Otherwise, it
returns NULL
char *fgets(char *str, int num, FILE *fp);
26
Misc. File I/O Functions
 fgets()
char s[5] ;
FILE* fp = fopen("abc.txt", "r" ) ;
fgets( s, 5, fp ) ;
123
1 2
1234567
27
Misc. File I/O Functions
 Difference between gets and fgets
– gets: read before ‘n’. Not store ‘n’
– fgets: read before ‘n’. Store also ‘n’
28
Accessing a File Randomly
 How to read the file again?
char c ;
FILE *fp = fopen("abc.txt", "r" ) ;
while( !foef(fp) ) {
fscanf( fp, "%c", &c ) ;
printf("%c", c ) ;
}
while( !foef(fp) ) {
fscanf( fp, "%c", &c ) ;
printf("%c", c ) ;
}
abcd
efghi
abc.txt
29
Accessing a File Randomly
 rewind()
– Move file position indicator
to the beginning of the file
void rewind( FILE* ) ;
char c ;
FILE *fp = fopen("abc.txt", “r” ) ;
while( !foef(fp) ) {
fscanf( fp, "%c", &c ) ;
printf("%c", c ) ;
}
rewind( fp ) ;
while( !foef(fp) ) {
fscanf( fp, "%c", &c ) ;
printf("%c", c ) ;
}
abcd
efghi
abc.txt
30
Accessing a File Randomly
 fseek()
– Move file position indicator to offset from place
– Value of place
0 (starting point of the file)
1 (current position)
2 (end of the file)
fseek( file_ptr, offset, place);
31
Accessing a File Randomly
 fseek()
fseek( file_ptr, offset, place);
0 (SEEK_SET)
1 (SEEK_CUR)
2 (SEEK_END)
0123456789
abcdefghjk
abc.txt
FILE *fp = fopen("abc.txt", “r” ) ;
fseek(fp, 3, SEEK_SET) ;
fseek(fp, 5, SEEK_CUR) ;
fseek(fp, -10, SEEK_END) ;
32
Accessing a File Randomly
 ftell()
– Return the current value of file position indicator
– Returned value is the number of bytes from the beginning of
the file
– Value of indicator is increased by one when it read a
character
int ftell( FILE* );
33
Accessing a File Randomly
 ftell()
char c ;
int pos ;
FILE *fp = fopen("abc.txt", “r” ) ;
while( !foef(fp) ) {
fscanf( fp, "%c", &c ) ;
printf("%d: %cn", ftell(fp), c ) ;
}
abcd
efghi
abc.txt
34
stdin, stdout & stderr
 Print output with fprintf
– stdout is a file pointer for monitor
 Read from keyboard with fscanf
– Stdin is a file pointer for keyboard
printf( “This is a testn” ) ; fprintf( stdout, “This is a testn” ) ;
scanf( “%d”, &k ) ; fscanf( stdin, “%d”, &k ) ;
35
stdin, stdout & stderr
Standard C files in stdio.h
Written in C Name Remark
stdin standard input file connected to the keyboard
stdout standard output file connected to the screen
stderr standard error file connected to the screen
 Three kinds of file pointer in stdio.h
36
stdin, stdout & stderr
#include <stdio.h>
void main() {
int k, j ;
fscanf( stdin, "%d %d", &k, &j ) ;
fprintf( stdout, "Sum: %dn", k + j ) ;
fprintf( stderr, "OKn") ;
}

More Related Content

What's hot (20)

File management
File managementFile management
File management
 
Satz1
Satz1Satz1
Satz1
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
file handling1
file handling1file handling1
file handling1
 
File in c
File in cFile in c
File in c
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File in C language
File in C languageFile in C language
File in C language
 
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 Management
File ManagementFile Management
File Management
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File handling in c
File handling in c File handling in c
File handling in c
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Unit 8
Unit 8Unit 8
Unit 8
 
C 檔案輸入與輸出
C 檔案輸入與輸出C 檔案輸入與輸出
C 檔案輸入與輸出
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
1file handling
1file handling1file handling
1file handling
 
File handling
File handlingFile handling
File handling
 

Viewers also liked

15 1. enumeration
15 1. enumeration15 1. enumeration
15 1. enumeration웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
12 1. const pointer, typedef
12 1. const pointer, typedef12 1. const pointer, typedef
12 1. const pointer, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer웅식 전
 

Viewers also liked (19)

15 1. enumeration
15 1. enumeration15 1. enumeration
15 1. enumeration
 
4. loop
4. loop4. loop
4. loop
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
6 function
6 function6 function
6 function
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
12 1. const pointer, typedef
12 1. const pointer, typedef12 1. const pointer, typedef
12 1. const pointer, typedef
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
Goorm class
Goorm classGoorm class
Goorm class
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
skku cp2 w4
skku cp2 w4skku cp2 w4
skku cp2 w4
 
6. functions
6. functions6. functions
6. functions
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
 
Cp2 w5
Cp2 w5Cp2 w5
Cp2 w5
 

Similar to 14. fiile io (20)

File handling-c
File handling-cFile handling-c
File handling-c
 
Chap 12(files)
Chap 12(files)Chap 12(files)
Chap 12(files)
 
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
File handling in cFile handling in c
File handling in c
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Files in C
Files in CFiles in C
Files in C
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
Vcs26
Vcs26Vcs26
Vcs26
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
File management and handling by prabhakar
File management and handling by prabhakarFile management and handling by prabhakar
File management and handling by prabhakar
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
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
 
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
 
Handout#01
Handout#01Handout#01
Handout#01
 
4 text file
4 text file4 text file
4 text file
 

More from 웅식 전

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 

More from 웅식 전 (20)

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
13. structure
13. structure13. structure
13. structure
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

14. fiile io

  • 2. 2 File Input/Output  Input/Output device for programs – Input: Keyboard – Output: Monitor  Is it possible to read or write data from/to files? A B C 1 80 90 70 2 80 60 40 3 60 50 70 … C program A B C Avg. 1 80 90 70 80 2 80 60 40 60 3 60 50 70 60 … read write file1.txt file2.txt
  • 3. 3 File Input/Ooutput  File Input/Output Process Open the file Read data from file Write data to file Close the file fopen fscanf, fprintf, fgets, fputs, … fclose
  • 4. 4 File Operation Function fopen()  fopen() – Used to prepare external files to use in programs • All files are associated with a data structure known as a stream if fopen successes – Return value: a pointer of FILE structure • File stream is manipulated with FILE pointer returned by fopen  fopen() Syntax FILE *fopen( const char *filename, const char *mode ); Return by file pointer Filename in disk File open mode
  • 5. 5 File Operation Function fopen()  Example – Open my_file.txt in the read mode – Return NULL at failure – Eg) If a file named “my_file.txt” does not exist FILE *fp ; fp = fopen(“my_file.txt”, “r”);
  • 6. 6 File Operation Function fopen()  Example – Open my_file.txt in the write mode – If my_file.txt does not exist, it is created – If my_file.txt exists, the content of the file is erased FILE *fp ; fp = fopen(“my_file.txt”, “w”);
  • 7. 7 File Operation Function fopen()  Example – Open my_file.txt in the append mode (similar to write mode) – If my_file.txt does not exist, it is created – If my_file.txt exists, the file content is kept and new data is appended at the end of file FILE *fp ; fp = fopen(“my_file.txt”, “a”);
  • 8. 8 File Operation Function fopen()  Example – Open my_file.txt in the read/write mode – Return NULL, if my_file.txt does not exist – If my_file.txt exists, the file content is kept – Read/write pointer is positioned at the beginning of the file FILE *fp ; fp = fopen(“my_file.txt”, “r+”);
  • 9. 9 File Operation Function fopen()  Example – Open my_file.txt in the read/write mode – If my_file.txt does not exist, it is created – If my_file.txt exists, the file content is erased FILE *fp ; fp = fopen(“my_file.txt”, “w+”);
  • 10. 10 File Operation Function fopen()  Example – Open my_file.txt in the read/write mode – If my_file.txt does not exist, it is created – If my_file.txt exists, the file content is kept – Read/write pointer is positioned at the end of the file FILE *fp ; fp = fopen(“my_file.txt”, “a+”);
  • 11. 11 File pointer  File pointer – File I/O is processed through file pointer  ‘FILE’ Type  a type of structure defined with typedef in stdio.h contains information of file [Ex] FILE *fp; /* declare ‘fp’ as file pointer */
  • 12. 12 File Operation Function fclose()  fclose() – Close the file opened by fopen  fclose() Syntax int fclose( FILE *stream ); file pointer returned by fopen Returns 0 : successful EOF : error (EOF is defined as –1 in stdio.h)
  • 13. 13 File Operation Function fopen()  fclose() Example #include <stdio.h> void main() { FILE *fp ; fp = fopen(“my_file.txt”, “r”); ... fclose( fp ) ; }
  • 14. 14 Formatted I/O Function fprintf()  fprintf() – printf() for file operation – First argument is the file pointer which has one of write modes (w, a, r+, w+, a+) – The rest arguments are the same as printf() – fprintf() writes data into abc.txt FILE* fp = fopen( “abc.txt”, “w” ) ; fprintf( fp, “%d %dn”, 1, 2 );
  • 15. 15 Formatted I/O Function fprintf()  fscanf() – scanf() for file operation – First argument is file pointer which has one of read modes (r, r+, w+, a+) – The rest arguments are the same as printf() – scanf() reads data from abc.txt int i, j ; FILE* fp = fopen( “abc.txt”, “r” ) ; fscanf( fp, “%d %d”, &i, &j );
  • 16. 16 feof() Function  feof() – Check whether the file pointer is at the end of file or not int feof( FILE *stream ); Opened file pointer Returns none-zero : if it is EOF 0 : if it is not EOF
  • 17. 17 Formatted I/O Function fprintf() and fscanf() #include <stdio.h> void main() { int i, j, k ; FILE *ifp, *ofp ; ifp = fopen("abc.txt", "r" ) ; ofp = fopen("cal.txt", "w" ) ; fscanf( ifp, "%d %d %d", &i, &j, &k ) ; fprintf( ofp, "sum: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; }  fprintf(), fscanf() Example 1 2 3 abc.txt cal.txt is not exist
  • 18. 18 Formatted I/O Function fprintf() and fscanf() #include <stdio.h> void main() { int i, j, k ; FILE *ifp, *ofp ; ifp = fopen("abc.txt", "r" ) ; ofp = fopen("cal.txt", "w" ) ; fscanf( ifp, "%d %d %d", &i, &j, &k ) ; fprintf( ofp, "sum: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; }  fprintf(), fscanf() Example 1 2 3 abc.txt sum: 6 cal.txt
  • 19. 19 Formatted I/O Function fprintf() and fscanf() #include <stdio.h> void main() { int i, j, k ; FILE *ifp, *ofp ; ifp = fopen("abc.txt", "r" ) ; ofp = fopen("cal.txt", "a" ) ; fscanf( ifp, "%d %d %d", &i, &j, &k ) ; fprintf( ofp, "sum: %dn", i + j + k ) ; fclose( ifp ) ; fclose( ofp ) ; }  fprintf(), fscanf() Example 1 2 3 abc.txt sum: 6 cal.txt
  • 20. 20 Formatted I/O Function fprintf() and fscanf() #include <stdio.h> void main() { char c ; FILE *ifp, *ofp ; ifp = fopen("abc.txt", "r" ) ; ofp = fopen("abc2.txt", "a" ) ; while( feof(ifp) == 0 ) { fscanf( ifp, "%c", &c ) ; fprintf( ofp, "%c", c ) ; } fclose( ifp ) ; fclose( ofp ) ; }  fprintf(), fscanf() Example This is a file. 1 2 3 abc.txt This is a file. 1 2 3 abc2.txt
  • 21. 21 Misc. File I/O Functions  fgetc() , getc() – Read a character from a file • If there is no more character to read, return EOF – fgetc() is equivalent to getc() char c ; FILE *fp = fopen("abc.txt", "r" ) ; while( (c = fgetc(fp)) != EOF ) printf("%c", c ) ; int fgetc ( FILE *stream ) ;
  • 22. 22 Misc. File I/O Functions  fputc() , putc() – Write a character to a file – fputc() is identical to putc() char c ; FILE *fp = fopen("abc.txt", "r" ) ; FILE *ofp = fopen("xyz.txt", "w" ) ; while( (c = fgetc(fp)) != EOF ) fputc( c, ofp ) ; int fputc ( int c, FILE *stream ) ;
  • 23. 23 Misc. File I/O Functions  fputs() : Writing a string – puts() for file I/O – Print a string into file – At success, it returns a non-negative value – At failure, it returns EOF int fputs(char *str, FILE *fp);
  • 24. 24 Misc. File I/O Functions FILE *fp; int i; char *data[3]={"to ben","or notn","to ben"}; fp = fopen("abc.txt", "w"); for(i = 0; i<3; i++) fputs(data[i],fp); fclose( fp );
  • 25. 25 Misc. File I/O Functions  fgets() : Reading a String – gets() for file I/O – Read (num -1) characters from fp and store to str – When fp meets ‘n’ or EOF, it stops reading and store NULL into str – At success, it returns the address of str. Otherwise, it returns NULL char *fgets(char *str, int num, FILE *fp);
  • 26. 26 Misc. File I/O Functions  fgets() char s[5] ; FILE* fp = fopen("abc.txt", "r" ) ; fgets( s, 5, fp ) ; 123 1 2 1234567
  • 27. 27 Misc. File I/O Functions  Difference between gets and fgets – gets: read before ‘n’. Not store ‘n’ – fgets: read before ‘n’. Store also ‘n’
  • 28. 28 Accessing a File Randomly  How to read the file again? char c ; FILE *fp = fopen("abc.txt", "r" ) ; while( !foef(fp) ) { fscanf( fp, "%c", &c ) ; printf("%c", c ) ; } while( !foef(fp) ) { fscanf( fp, "%c", &c ) ; printf("%c", c ) ; } abcd efghi abc.txt
  • 29. 29 Accessing a File Randomly  rewind() – Move file position indicator to the beginning of the file void rewind( FILE* ) ; char c ; FILE *fp = fopen("abc.txt", “r” ) ; while( !foef(fp) ) { fscanf( fp, "%c", &c ) ; printf("%c", c ) ; } rewind( fp ) ; while( !foef(fp) ) { fscanf( fp, "%c", &c ) ; printf("%c", c ) ; } abcd efghi abc.txt
  • 30. 30 Accessing a File Randomly  fseek() – Move file position indicator to offset from place – Value of place 0 (starting point of the file) 1 (current position) 2 (end of the file) fseek( file_ptr, offset, place);
  • 31. 31 Accessing a File Randomly  fseek() fseek( file_ptr, offset, place); 0 (SEEK_SET) 1 (SEEK_CUR) 2 (SEEK_END) 0123456789 abcdefghjk abc.txt FILE *fp = fopen("abc.txt", “r” ) ; fseek(fp, 3, SEEK_SET) ; fseek(fp, 5, SEEK_CUR) ; fseek(fp, -10, SEEK_END) ;
  • 32. 32 Accessing a File Randomly  ftell() – Return the current value of file position indicator – Returned value is the number of bytes from the beginning of the file – Value of indicator is increased by one when it read a character int ftell( FILE* );
  • 33. 33 Accessing a File Randomly  ftell() char c ; int pos ; FILE *fp = fopen("abc.txt", “r” ) ; while( !foef(fp) ) { fscanf( fp, "%c", &c ) ; printf("%d: %cn", ftell(fp), c ) ; } abcd efghi abc.txt
  • 34. 34 stdin, stdout & stderr  Print output with fprintf – stdout is a file pointer for monitor  Read from keyboard with fscanf – Stdin is a file pointer for keyboard printf( “This is a testn” ) ; fprintf( stdout, “This is a testn” ) ; scanf( “%d”, &k ) ; fscanf( stdin, “%d”, &k ) ;
  • 35. 35 stdin, stdout & stderr Standard C files in stdio.h Written in C Name Remark stdin standard input file connected to the keyboard stdout standard output file connected to the screen stderr standard error file connected to the screen  Three kinds of file pointer in stdio.h
  • 36. 36 stdin, stdout & stderr #include <stdio.h> void main() { int k, j ; fscanf( stdin, "%d %d", &k, &j ) ; fprintf( stdout, "Sum: %dn", k + j ) ; fprintf( stderr, "OKn") ; }