SlideShare a Scribd company logo
1 of 34
1
File I/OFile I/O
TA: Liao Ping-LunTA: Liao Ping-Lun
2
Answer to the last questionAnswer to the last question
Two Parameters in _beginthreadTwo Parameters in _beginthread
3
AgendaAgenda
IntroductionIntroduction
StreamsStreams
FILE pointersFILE pointers
Opening and ClosingOpening and Closing
FilesFiles
Other file accessOther file access
functionsfunctions
Functions that Modify theFunctions that Modify the
File Position IndicatorFile Position Indicator
Error Handling FunctionsError Handling Functions
Other Operations on FilesOther Operations on Files
Reading from FilesReading from Files
Writing to FilesWriting to Files
4
IntroductionIntroduction
Header file: stdio.h ( ANSI C )Header file: stdio.h ( ANSI C )
#include <stdio.h>#include <stdio.h>
StStandarandardd IInput/nput/OOutpututput
Q: Does C Language Support I/O ?Q: Does C Language Support I/O ?
5
StreamsStreams
Logical data streamsLogical data streams
Text streamsText streams
Binary streamsBinary streams
Disk Disk
Stream
Read Write
6
DemoDemo
stdinstdin
stdoutstdout
7
FILE pointersFILE pointers
Recording all the information needed to controlRecording all the information needed to control
a stream.a stream.
File position indicator.File position indicator.
An error indicator.An error indicator.
An end-of-file indicator.An end-of-file indicator.
8
FILE pointersFILE pointers
It is considered bad manners to access the contIt is considered bad manners to access the cont
ents of FILE directly unless the programmer isents of FILE directly unless the programmer is
writing an implementation of <stdio.h> and itswriting an implementation of <stdio.h> and its
contents. How, pray tell, is one going to knowcontents. How, pray tell, is one going to know
whether the file handle, for example, is spelt hawhether the file handle, for example, is spelt ha
ndle or _Handle? Access to the contents of FILndle or _Handle? Access to the contents of FIL
E is better provided via the functions in <stdio.E is better provided via the functions in <stdio.
h>h>
9
Sample CodeSample Code
FILE *inFile, *outFile;FILE *inFile, *outFile;
10
Opening and Closing FilesOpening and Closing Files
Opening FilesOpening Files
FILE *fopen(const char *filename, const char *mode);FILE *fopen(const char *filename, const char *mode);
FILE *freopen(const char *filename, const char *mode, FILFILE *freopen(const char *filename, const char *mode, FIL
E *stream);E *stream);
11
Opening and Closing FilesOpening and Closing Files
ModeMode
r : open a text file for readingr : open a text file for reading
w : truncate to zero length or create a text file for writingw : truncate to zero length or create a text file for writing
a : append; open or create text file for writing at end-of-filea : append; open or create text file for writing at end-of-file
rb : open binary file for reading wb truncate to zero length orb : open binary file for reading wb truncate to zero length o
r create a binary file for writingr create a binary file for writing
ab : append; open or create binary file for writing at end-of-ab : append; open or create binary file for writing at end-of-
filefile
12
Opening and Closing FilesOpening and Closing Files
ModeMode
r+ : open text file for update (reading and writing)r+ : open text file for update (reading and writing)
w+ : truncate to zero length or create a text file for updatew+ : truncate to zero length or create a text file for update
a+ : append; open or create text file for updatea+ : append; open or create text file for update
r+b or rb+ : open binary file for update (reading and writinr+b or rb+ : open binary file for update (reading and writin
g)g)
w+b or wb+ : truncate to zero length or create a binary file fw+b or wb+ : truncate to zero length or create a binary file f
or updateor update
a+b or ab+ : append; open or create binary file for updatea+b or ab+ : append; open or create binary file for update
13
Opening and Closing FilesOpening and Closing Files
Opening FilesOpening Files
The fopen function returns a pointer to the object cThe fopen function returns a pointer to the object c
ontrolling the stream. If the open operation fails, foontrolling the stream. If the open operation fails, fo
pen returns a null pointer.pen returns a null pointer.
The freopen function opens the file whose name is tThe freopen function opens the file whose name is t
he string pointed to by filename and associates thehe string pointed to by filename and associates the
stream pointed to by stream with it. The mode argustream pointed to by stream with it. The mode argu
ment is used just as in the fopen function.ment is used just as in the fopen function.
14
Opening and Closing FilesOpening and Closing Files
Opening FilesOpening Files
The freopen function first attempts to close any fileThe freopen function first attempts to close any file
that is associated with the specified stream. Failurethat is associated with the specified stream. Failure
to close the file successfully is ignored. The error ato close the file successfully is ignored. The error a
nd end-of-file indicators for the stream are cleared.nd end-of-file indicators for the stream are cleared.
The freopen function returns a null pointer if the opThe freopen function returns a null pointer if the op
en operation fails, or the value stream if the open oen operation fails, or the value stream if the open o
peration succeeds.peration succeeds.
15
Sample CodeSample Code
inFile = fopen( argv[1], "r" );inFile = fopen( argv[1], "r" );
outFile = fopen( argv[2], "w" );outFile = fopen( argv[2], "w" );
16
Opening and Closing FilesOpening and Closing Files
Closing FilesClosing Files
int fclose(FILE *stream);int fclose(FILE *stream);
The fclose function causes the stream pointed to by strThe fclose function causes the stream pointed to by str
eam to be flushed and the associated file to be closed.eam to be flushed and the associated file to be closed.
Any unwritten buffered data for the stream are deliverAny unwritten buffered data for the stream are deliver
ed to the host environment to be written to the file; aned to the host environment to be written to the file; an
y unread buffered data are discarded.y unread buffered data are discarded.
The stream is disassociated from the file.The stream is disassociated from the file.
If the associated buffer was automatically allocated, itIf the associated buffer was automatically allocated, it
is deallocated.is deallocated.
The function returns zero if the stream was successfullThe function returns zero if the stream was successfull
y closed or EOF if any errors were detected.y closed or EOF if any errors were detected.
17
Sample CodeSample Code
fclose( inFile );fclose( inFile );
fclose( outFile );fclose( outFile );
18
Other file access functionsOther file access functions
The fflush functionThe fflush function
int fflush(FILE *stream);int fflush(FILE *stream);
The setbuf functionThe setbuf function
void setbuf(FILE *stream, char *buf);void setbuf(FILE *stream, char *buf);
The setvbuf functionThe setvbuf function
int setvbuf(FILE *stream, char *buf, int mode, sizeint setvbuf(FILE *stream, char *buf, int mode, size
_t size);_t size);
19
Sample CodeSample Code
char c;char c;
scanf("%c", &c);scanf("%c", &c);
printf("%cn", c);printf("%cn", c);
fflush(stdin);fflush(stdin);
scanf("%c", &c);scanf("%c", &c);
printf("%cn", c);printf("%cn", c);
20
Functions that Modify the FileFunctions that Modify the File
Position IndicatorPosition Indicator
The fgetpos and fsetpos functionsThe fgetpos and fsetpos functions
int fgetpos(FILE *stream, fpos_t *pos);int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, const fpos_t *pos);int fsetpos(FILE *stream, const fpos_t *pos);
The fseek and ftell functionsThe fseek and ftell functions
int fseek(FILE *stream, long int offset, int whence)int fseek(FILE *stream, long int offset, int whence)
;;
long int ftell(FILE *stream);long int ftell(FILE *stream);
The rewind functionThe rewind function
void rewind(FILE *stream);void rewind(FILE *stream);
21
Sample CodeSample Code
fpos_t curPos;fpos_t curPos;
if( fgetpos( inFile, &curPos ) )if( fgetpos( inFile, &curPos ) )
{{
printf("fgetpos error.n");printf("fgetpos error.n");
exit(1);exit(1);
}}
22
Sample CodeSample Code
if( fsetpos( inFile, &savedPos ) )if( fsetpos( inFile, &savedPos ) )
{{
printf("fsetpos error.n");printf("fsetpos error.n");
exit(1);exit(1);
}}
23
Sample CodeSample Code
if( fseek( inFile, 3, SEEK_SET ) )if( fseek( inFile, 3, SEEK_SET ) )
{{
printf("fseek error.n");printf("fseek error.n");
exit(1);exit(1);
}}
24
Error Handling FunctionsError Handling Functions
The clearerr functionThe clearerr function
void clearerr(FILE *stream);void clearerr(FILE *stream);
The feof functionThe feof function
int feof(FILE *stream);int feof(FILE *stream);
The ferror functionThe ferror function
int ferror(FILE *stream);int ferror(FILE *stream);
The perror functionThe perror function
void perror(const char *s);void perror(const char *s);
25
Sample CodeSample Code
while( !feof( inFile ) )while( !feof( inFile ) )
{{
int c = getc( inFile );int c = getc( inFile );
putc( c, outFile );putc( c, outFile );
}}
26
Other Operations on FilesOther Operations on Files
The remove functionThe remove function
int remove(const char *filename);int remove(const char *filename);
The rename functionThe rename function
int rename(const char *old_filename, const char *nint rename(const char *old_filename, const char *n
ew_filename);ew_filename);
The tmpfile functionThe tmpfile function
FILE *tmpfile(void);FILE *tmpfile(void);
The tmpnam functionThe tmpnam function
char *tmpnam(char *s);char *tmpnam(char *s);
27
Sample CodeSample Code
if( remove( argv[2] ) )if( remove( argv[2] ) )
{{
printf("Can't remove the file: %sn", argv[2] );printf("Can't remove the file: %sn", argv[2] );
exit(1);exit(1);
}}
28
Sample CodeSample Code
if( rename( argv[1], "Text2.txt" ) )if( rename( argv[1], "Text2.txt" ) )
{{
printf("Can't remove the file: %sn", argv[2] );printf("Can't remove the file: %sn", argv[2] );
exit(1);exit(1);
}}
29
Reading from FilesReading from Files
The fgetc functionThe fgetc function
int fputc(int c, FILE *strint fputc(int c, FILE *str
eam);eam);
The fgets functionThe fgets function
int fputs(const char *s, Fint fputs(const char *s, F
ILE *stream);ILE *stream);
The getc functionThe getc function
int getc(FILE *stream);int getc(FILE *stream);
The getchar functionThe getchar function
int getchar(void);int getchar(void);
The gets functionThe gets function
char *gets(char *s);char *gets(char *s);
The ungetc functionThe ungetc function
int ungetc(int c, FILE *stint ungetc(int c, FILE *st
ream);ream);
30
Writing to FilesWriting to Files
The fputc functionThe fputc function
int fputc(int c, FILE *strint fputc(int c, FILE *str
eam);eam);
The fputs functionThe fputs function
int fputs(const char *s, Fint fputs(const char *s, F
ILE *stream);ILE *stream);
The putc functionThe putc function
int putc(int c, FILE *streint putc(int c, FILE *stre
am);am);
The putchar functionThe putchar function
int putchar(int c);int putchar(int c);
The puts functionThe puts function
int puts(const char *s);int puts(const char *s);
31
Sample CodeSample Code
int c;int c;
while( (c = getc( inFile )) != EOF )while( (c = getc( inFile )) != EOF )
{{
putc( c, outFile );putc( c, outFile );
}}
32
Code ExampleCode Example
ExampleExample
FileIO_DemoFileIO_Demo
33
Q & AQ & A
34
ReferencesReferences
wikiwiki
http://http://
en.wikibooks.org/wiki/C_Programming/File_IOen.wikibooks.org/wiki/C_Programming/File_IO
Standard C I/OStandard C I/O
http://www.cppreference.com/stdio/index.htmlhttp://www.cppreference.com/stdio/index.html

More Related Content

What's hot (20)

File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
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
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
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
Unit5Unit5
Unit5
 
File management
File managementFile management
File management
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
Python-files
Python-filesPython-files
Python-files
 
Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
Unit v
Unit vUnit v
Unit v
 
1file handling
1file handling1file handling
1file handling
 
File accessing modes in c
File accessing modes in cFile accessing modes in c
File accessing modes in c
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 

Similar to C 檔案輸入與輸出 (20)

PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Topic - File operation.pptx
Topic - File operation.pptxTopic - File operation.pptx
Topic - File operation.pptx
 
File handling C program
File handling C programFile handling C program
File handling C program
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
File in c
File in cFile in c
File in c
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
File management
File managementFile management
File management
 
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 handling-c
File handling-cFile handling-c
File handling-c
 
File handling in c
File handling in cFile handling in c
File handling in 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
 
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
 
Python Files I_O17.pdf
Python Files I_O17.pdfPython Files I_O17.pdf
Python Files I_O17.pdf
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Handout#01
Handout#01Handout#01
Handout#01
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Programming in C
Programming in CProgramming in C
Programming in C
 

More from PingLun Liao

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言PingLun Liao
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹PingLun Liao
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人PingLun Liao
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For BioinformaticsPingLun Liao
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎PingLun Liao
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用PingLun Liao
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎PingLun Liao
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計PingLun Liao
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計PingLun Liao
 
Android introduction
Android introductionAndroid introduction
Android introductionPingLun Liao
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic ProgrammingPingLun Liao
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented ProgrammingPingLun Liao
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part IIPingLun Liao
 

More from PingLun Liao (20)

深入探討 C 語言
深入探討 C 語言深入探討 C 語言
深入探討 C 語言
 
Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹Git 程式碼版本控制軟體介紹
Git 程式碼版本控制軟體介紹
 
給沒有程式設計經驗的人
給沒有程式設計經驗的人給沒有程式設計經驗的人
給沒有程式設計經驗的人
 
陣列與指標
陣列與指標陣列與指標
陣列與指標
 
Perl For Bioinformatics
Perl For BioinformaticsPerl For Bioinformatics
Perl For Bioinformatics
 
C++ STL 概觀
C++ STL 概觀C++ STL 概觀
C++ STL 概觀
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Win32 視窗程式設計基礎
Win32 視窗程式設計基礎Win32 視窗程式設計基礎
Win32 視窗程式設計基礎
 
Matlab 在機率與統計的應用
Matlab 在機率與統計的應用Matlab 在機率與統計的應用
Matlab 在機率與統計的應用
 
Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎Android 2D 遊戲設計基礎
Android 2D 遊戲設計基礎
 
Android 介面設計
Android 介面設計Android 介面設計
Android 介面設計
 
Java 視窗程式設計
Java 視窗程式設計Java 視窗程式設計
Java 視窗程式設計
 
Java 網路程式
Java 網路程式Java 網路程式
Java 網路程式
 
Android introduction
Android introductionAndroid introduction
Android introduction
 
RESTful
RESTfulRESTful
RESTful
 
Web service
Web serviceWeb service
Web service
 
How toprogram
How toprogramHow toprogram
How toprogram
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented Programming
 
Object-Based Programming Part II
Object-Based Programming Part IIObject-Based Programming Part II
Object-Based Programming Part II
 

Recently uploaded

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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
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
 
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
 

Recently uploaded (20)

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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
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
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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 ...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
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?
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

C 檔案輸入與輸出

  • 1. 1 File I/OFile I/O TA: Liao Ping-LunTA: Liao Ping-Lun
  • 2. 2 Answer to the last questionAnswer to the last question Two Parameters in _beginthreadTwo Parameters in _beginthread
  • 3. 3 AgendaAgenda IntroductionIntroduction StreamsStreams FILE pointersFILE pointers Opening and ClosingOpening and Closing FilesFiles Other file accessOther file access functionsfunctions Functions that Modify theFunctions that Modify the File Position IndicatorFile Position Indicator Error Handling FunctionsError Handling Functions Other Operations on FilesOther Operations on Files Reading from FilesReading from Files Writing to FilesWriting to Files
  • 4. 4 IntroductionIntroduction Header file: stdio.h ( ANSI C )Header file: stdio.h ( ANSI C ) #include <stdio.h>#include <stdio.h> StStandarandardd IInput/nput/OOutpututput Q: Does C Language Support I/O ?Q: Does C Language Support I/O ?
  • 5. 5 StreamsStreams Logical data streamsLogical data streams Text streamsText streams Binary streamsBinary streams Disk Disk Stream Read Write
  • 7. 7 FILE pointersFILE pointers Recording all the information needed to controlRecording all the information needed to control a stream.a stream. File position indicator.File position indicator. An error indicator.An error indicator. An end-of-file indicator.An end-of-file indicator.
  • 8. 8 FILE pointersFILE pointers It is considered bad manners to access the contIt is considered bad manners to access the cont ents of FILE directly unless the programmer isents of FILE directly unless the programmer is writing an implementation of <stdio.h> and itswriting an implementation of <stdio.h> and its contents. How, pray tell, is one going to knowcontents. How, pray tell, is one going to know whether the file handle, for example, is spelt hawhether the file handle, for example, is spelt ha ndle or _Handle? Access to the contents of FILndle or _Handle? Access to the contents of FIL E is better provided via the functions in <stdio.E is better provided via the functions in <stdio. h>h>
  • 9. 9 Sample CodeSample Code FILE *inFile, *outFile;FILE *inFile, *outFile;
  • 10. 10 Opening and Closing FilesOpening and Closing Files Opening FilesOpening Files FILE *fopen(const char *filename, const char *mode);FILE *fopen(const char *filename, const char *mode); FILE *freopen(const char *filename, const char *mode, FILFILE *freopen(const char *filename, const char *mode, FIL E *stream);E *stream);
  • 11. 11 Opening and Closing FilesOpening and Closing Files ModeMode r : open a text file for readingr : open a text file for reading w : truncate to zero length or create a text file for writingw : truncate to zero length or create a text file for writing a : append; open or create text file for writing at end-of-filea : append; open or create text file for writing at end-of-file rb : open binary file for reading wb truncate to zero length orb : open binary file for reading wb truncate to zero length o r create a binary file for writingr create a binary file for writing ab : append; open or create binary file for writing at end-of-ab : append; open or create binary file for writing at end-of- filefile
  • 12. 12 Opening and Closing FilesOpening and Closing Files ModeMode r+ : open text file for update (reading and writing)r+ : open text file for update (reading and writing) w+ : truncate to zero length or create a text file for updatew+ : truncate to zero length or create a text file for update a+ : append; open or create text file for updatea+ : append; open or create text file for update r+b or rb+ : open binary file for update (reading and writinr+b or rb+ : open binary file for update (reading and writin g)g) w+b or wb+ : truncate to zero length or create a binary file fw+b or wb+ : truncate to zero length or create a binary file f or updateor update a+b or ab+ : append; open or create binary file for updatea+b or ab+ : append; open or create binary file for update
  • 13. 13 Opening and Closing FilesOpening and Closing Files Opening FilesOpening Files The fopen function returns a pointer to the object cThe fopen function returns a pointer to the object c ontrolling the stream. If the open operation fails, foontrolling the stream. If the open operation fails, fo pen returns a null pointer.pen returns a null pointer. The freopen function opens the file whose name is tThe freopen function opens the file whose name is t he string pointed to by filename and associates thehe string pointed to by filename and associates the stream pointed to by stream with it. The mode argustream pointed to by stream with it. The mode argu ment is used just as in the fopen function.ment is used just as in the fopen function.
  • 14. 14 Opening and Closing FilesOpening and Closing Files Opening FilesOpening Files The freopen function first attempts to close any fileThe freopen function first attempts to close any file that is associated with the specified stream. Failurethat is associated with the specified stream. Failure to close the file successfully is ignored. The error ato close the file successfully is ignored. The error a nd end-of-file indicators for the stream are cleared.nd end-of-file indicators for the stream are cleared. The freopen function returns a null pointer if the opThe freopen function returns a null pointer if the op en operation fails, or the value stream if the open oen operation fails, or the value stream if the open o peration succeeds.peration succeeds.
  • 15. 15 Sample CodeSample Code inFile = fopen( argv[1], "r" );inFile = fopen( argv[1], "r" ); outFile = fopen( argv[2], "w" );outFile = fopen( argv[2], "w" );
  • 16. 16 Opening and Closing FilesOpening and Closing Files Closing FilesClosing Files int fclose(FILE *stream);int fclose(FILE *stream); The fclose function causes the stream pointed to by strThe fclose function causes the stream pointed to by str eam to be flushed and the associated file to be closed.eam to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are deliverAny unwritten buffered data for the stream are deliver ed to the host environment to be written to the file; aned to the host environment to be written to the file; an y unread buffered data are discarded.y unread buffered data are discarded. The stream is disassociated from the file.The stream is disassociated from the file. If the associated buffer was automatically allocated, itIf the associated buffer was automatically allocated, it is deallocated.is deallocated. The function returns zero if the stream was successfullThe function returns zero if the stream was successfull y closed or EOF if any errors were detected.y closed or EOF if any errors were detected.
  • 17. 17 Sample CodeSample Code fclose( inFile );fclose( inFile ); fclose( outFile );fclose( outFile );
  • 18. 18 Other file access functionsOther file access functions The fflush functionThe fflush function int fflush(FILE *stream);int fflush(FILE *stream); The setbuf functionThe setbuf function void setbuf(FILE *stream, char *buf);void setbuf(FILE *stream, char *buf); The setvbuf functionThe setvbuf function int setvbuf(FILE *stream, char *buf, int mode, sizeint setvbuf(FILE *stream, char *buf, int mode, size _t size);_t size);
  • 19. 19 Sample CodeSample Code char c;char c; scanf("%c", &c);scanf("%c", &c); printf("%cn", c);printf("%cn", c); fflush(stdin);fflush(stdin); scanf("%c", &c);scanf("%c", &c); printf("%cn", c);printf("%cn", c);
  • 20. 20 Functions that Modify the FileFunctions that Modify the File Position IndicatorPosition Indicator The fgetpos and fsetpos functionsThe fgetpos and fsetpos functions int fgetpos(FILE *stream, fpos_t *pos);int fgetpos(FILE *stream, fpos_t *pos); int fsetpos(FILE *stream, const fpos_t *pos);int fsetpos(FILE *stream, const fpos_t *pos); The fseek and ftell functionsThe fseek and ftell functions int fseek(FILE *stream, long int offset, int whence)int fseek(FILE *stream, long int offset, int whence) ;; long int ftell(FILE *stream);long int ftell(FILE *stream); The rewind functionThe rewind function void rewind(FILE *stream);void rewind(FILE *stream);
  • 21. 21 Sample CodeSample Code fpos_t curPos;fpos_t curPos; if( fgetpos( inFile, &curPos ) )if( fgetpos( inFile, &curPos ) ) {{ printf("fgetpos error.n");printf("fgetpos error.n"); exit(1);exit(1); }}
  • 22. 22 Sample CodeSample Code if( fsetpos( inFile, &savedPos ) )if( fsetpos( inFile, &savedPos ) ) {{ printf("fsetpos error.n");printf("fsetpos error.n"); exit(1);exit(1); }}
  • 23. 23 Sample CodeSample Code if( fseek( inFile, 3, SEEK_SET ) )if( fseek( inFile, 3, SEEK_SET ) ) {{ printf("fseek error.n");printf("fseek error.n"); exit(1);exit(1); }}
  • 24. 24 Error Handling FunctionsError Handling Functions The clearerr functionThe clearerr function void clearerr(FILE *stream);void clearerr(FILE *stream); The feof functionThe feof function int feof(FILE *stream);int feof(FILE *stream); The ferror functionThe ferror function int ferror(FILE *stream);int ferror(FILE *stream); The perror functionThe perror function void perror(const char *s);void perror(const char *s);
  • 25. 25 Sample CodeSample Code while( !feof( inFile ) )while( !feof( inFile ) ) {{ int c = getc( inFile );int c = getc( inFile ); putc( c, outFile );putc( c, outFile ); }}
  • 26. 26 Other Operations on FilesOther Operations on Files The remove functionThe remove function int remove(const char *filename);int remove(const char *filename); The rename functionThe rename function int rename(const char *old_filename, const char *nint rename(const char *old_filename, const char *n ew_filename);ew_filename); The tmpfile functionThe tmpfile function FILE *tmpfile(void);FILE *tmpfile(void); The tmpnam functionThe tmpnam function char *tmpnam(char *s);char *tmpnam(char *s);
  • 27. 27 Sample CodeSample Code if( remove( argv[2] ) )if( remove( argv[2] ) ) {{ printf("Can't remove the file: %sn", argv[2] );printf("Can't remove the file: %sn", argv[2] ); exit(1);exit(1); }}
  • 28. 28 Sample CodeSample Code if( rename( argv[1], "Text2.txt" ) )if( rename( argv[1], "Text2.txt" ) ) {{ printf("Can't remove the file: %sn", argv[2] );printf("Can't remove the file: %sn", argv[2] ); exit(1);exit(1); }}
  • 29. 29 Reading from FilesReading from Files The fgetc functionThe fgetc function int fputc(int c, FILE *strint fputc(int c, FILE *str eam);eam); The fgets functionThe fgets function int fputs(const char *s, Fint fputs(const char *s, F ILE *stream);ILE *stream); The getc functionThe getc function int getc(FILE *stream);int getc(FILE *stream); The getchar functionThe getchar function int getchar(void);int getchar(void); The gets functionThe gets function char *gets(char *s);char *gets(char *s); The ungetc functionThe ungetc function int ungetc(int c, FILE *stint ungetc(int c, FILE *st ream);ream);
  • 30. 30 Writing to FilesWriting to Files The fputc functionThe fputc function int fputc(int c, FILE *strint fputc(int c, FILE *str eam);eam); The fputs functionThe fputs function int fputs(const char *s, Fint fputs(const char *s, F ILE *stream);ILE *stream); The putc functionThe putc function int putc(int c, FILE *streint putc(int c, FILE *stre am);am); The putchar functionThe putchar function int putchar(int c);int putchar(int c); The puts functionThe puts function int puts(const char *s);int puts(const char *s);
  • 31. 31 Sample CodeSample Code int c;int c; while( (c = getc( inFile )) != EOF )while( (c = getc( inFile )) != EOF ) {{ putc( c, outFile );putc( c, outFile ); }}
  • 33. 33 Q & AQ & A