Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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

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