File IO fopen p FILE fopen const char

  • Slides: 30
Download presentation
File I/O

File I/O

fopen() p FILE* fopen( const char* filename, const char* mode ) n The fopen()

fopen() p FILE* fopen( const char* filename, const char* mode ) n The fopen() function opens a file indicated by filename and returns a stream associated with that file. mode is used to determine how the file will be treated (i. e. for input, output, etc). 2

fclose() p int fclose ( FILE* stream ) n n The function fclose() closes

fclose() p int fclose ( FILE* stream ) n n The function fclose() closes the given file stream, deallocating any buffers associated with that stream. fclose() returns 0 upon success, and EOF otherwise. 3

fputs() p int fputs ( const char* str, FILE* stream ) n n The

fputs() p int fputs ( const char* str, FILE* stream ) n n The fputs() function writes a string str to the given output stream. The return value is non-negative on success, and EOF on failure. 4

Example: fputs() #include <iostream> If you run the program from Visual C++, it will

Example: fputs() #include <iostream> If you run the program from Visual C++, it will be created in the same directory as your CPP file. int main() { FILE* p. File; p. File = fopen("myfile. txt", "w"); if (p. File != NULL) { fputs("fopen successfullyn", p. File); fputs("Output by fputs(). n", p. File); fclose(p. File); } return 0; } 5

Inspect the text file p In the command window, n Change directory to the

Inspect the text file p In the command window, n Change directory to the working directory p n n For example, if your EXE file is "D: Visual. Studeio 2010ProjectstestDebugtest. exe", then run "test. exe" to generate the file "myfile. txt" in "D: Visual. Studeio 2010ProjectstestDebug" Inspect the content by “type myfile. txt” Edit the file by “notepad myfile. txt” 6

filename of fopen() p FILE* fopen( const char* filename, const char* mode ) n

filename of fopen() p FILE* fopen( const char* filename, const char* mode ) n If you provide a simple filename like "myfile. txt", it will refer to a file in the same directory as your CPP file. n You may specify an absolute path name like "D: \myfile. txt" p Remember to use double backslashes to escape the character. 7

fprintf() and printf() int printf(const char * restrict format, . . . ); p

fprintf() and printf() int printf(const char * restrict format, . . . ); p int fprintf (FILE* stream, const char * format, . . . ) p n n n The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes. The return value of fprintf() is the number of characters outputted, or a negative number if an error occurs. 8

Example: fprintf () /* fprintf() example */ #include <iostream> int main () { FILE*

Example: fprintf () /* fprintf() example */ #include <iostream> int main () { FILE* p. File; p. File = fopen("myfile. txt", "w"); if (p. File == NULL) { printf("Cannot open file!n"); } else { for (int i=1; i<15; i+=3) fprintf (p. File, "Output: %02 dn", i); fclose (p. File); } return 0; } Output: Output: 01 04 07 10 13 9

Format of printf() p A format string, which consists of optional and required fields,

Format of printf() p A format string, which consists of optional and required fields, has the following form: n p %[flags] [width] [. precision] type n determines the associated argument is interpreted as a character, a string, or a number (see the "printf Type Field Characters" table in printf Type Field Characters). p p p c – character s – string d – decimal x – hexadecimal o - octal http: //msdn. microsoft. com/en-us/library/56 e 442 dc. aspx 10

Format of printf() p flags n control justification of output and printing of signs,

Format of printf() p flags n control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see the "Flag Characters" table in Flag Directives). More than one flag can appear in a format specification. p p 0 (zero-padding) - (left adjustment) + (always put a sign before a number) width n p (cont. ) specifies the minimum number of characters output (see printf Width Specification). precision n specifies the number of digits to appear after the decimal point, for e and f formats. p p printf("%5. 2 fn", 99. 99); printf("%05. 2 fn", 9. 9); 99. 99 09. 90 11

Example of Format Specification // Format of printf() #include <iostream> int main () {

Example of Format Specification // Format of printf() #include <iostream> int main () { int i; char* a[] = { "Apple", "Banana", "Car" }; for (i=0; i< sizeof(a)/sizeof(a[0]); i++) printf("|%s|n", a[i]); printf("n"); for (i=0; i< sizeof(a)/sizeof(a[0]); i++) printf("|%10 s|n", a[i]); printf("n"); for (i=0; i< sizeof(a)/sizeof(a[0]); i++) printf("|%-10 s|n", a[i]); printf("n"); return 0; } |Apple| |Banana| |Car| | Apple| Banana| Car| |Apple |Banana |Car | | | 12

Example of fprintf() /* fprintf example */ #include <iostream> using std: : cout; using

Example of fprintf() /* fprintf example */ #include <iostream> using std: : cout; using std: : cin; int main() { FILE * p. File; int n; char name[40]; p. File = fopen("myfile. txt", "w"); for (n=0 ; n<3 ; n++) { cout << "please, enter a name: "; cin >> name; fprintf (p. File, "Name %d [%-6 s]n", n, name); } fclose (p. File); return 0; } 13

fgets() p char * fgets ( char * str, int num, FILE * stream

fgets() p char * fgets ( char * str, int num, FILE * stream ); n n Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. num - Maximum number of characters to be copied into str (including the terminating null-character). A terminating null ('') character is automatically appended after the characters copied to str. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. 14

Example: fgets() #include <iostream> int main() { FILE* fd; char str[10]; fd = fopen("test.

Example: fgets() #include <iostream> int main() { FILE* fd; char str[10]; fd = fopen("test. txt", "w"); fputs("HELLOn", fd); fputs("NCNUn", fd); fclose(fd); fd = fopen("test. txt", "r"); H E L L O n fgets(str, 10, fd); printf("%d - %s", strlen(str), str); 6 - HELLO return 0; } 15

Input: scanf() and fscanf() int scanf(const char* format, . . . ); p int

Input: scanf() and fscanf() int scanf(const char* format, . . . ); p int fscanf(FILE* stream, const char* format, . . . ); p n A format specification has the following form: p n %[*] [width] type A format specification causes scanf to read and convert characters in the input into values of a specified type. The value is assigned to an argument in the argument list. 16

Example of fscanf() /* fscanf() example */ #include <iostream> using std: : cout; Alice

Example of fscanf() /* fscanf() example */ #include <iostream> using std: : cout; Alice 170 Bob 165 Charlie 173 Dennis 188 int main() { FILE * p. File; int h; char name[40]; p. File = fopen("height. txt", "r"); while (fscanf(p. File, "%s %d", name, &h) != EOF) { cout << "The height of " << name << " is " << h << 'n'; } fclose (p. File); return 0; } 17

Format String for scanf() p The format argument can contain one or more of

Format String for scanf() p The format argument can contain one or more of the following: n White-space characters: blank (' '); tab ('t'); or newline ('n'). p p n A white-space character causes scanf to read, but not store, all consecutive white-space characters in the input up to the next non–white-space character. One white-space character in the format matches any number (including 0) and combination of white-space characters in the input. Non–white-space characters, except for the percent sign (%). p p A non–white-space character causes scanf to read, but not store, a matching non–white-space character. If the next character in the input stream does not match, 18 scanf terminates.

rename() p int rename(const char *from, const char *to); n Change the file/directory from

rename() p int rename(const char *from, const char *to); n Change the file/directory from to be renamed as to. p p n On Unix, if to exists, it is first removed. On Windows, if to exists, the function returns a nonzero value and sets errno to EACCESS. Both from and to must be of the same type p that is, both directories or both non-directories n and must reside on the same file system. n The rename() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. 19

Reference MSDN Function Reference http: //msdn. microsoft. com/enus/library/634 ca 0 c 2. aspx p

Reference MSDN Function Reference http: //msdn. microsoft. com/enus/library/634 ca 0 c 2. aspx p cstdio (stdio. h) – C++ Reference http: //www. cplus. com/reference/clibr ary/cstdio/ p Standard C I/O [C++ Reference] http: //www. cppreference. com/wiki/c/io/st art p 20

Exercise Sequentially read a text file “myfile. txt” line-by-line. p Store its contents in

Exercise Sequentially read a text file “myfile. txt” line-by-line. p Store its contents in the reverse order. p Alice Bob Charlie Dennis Charlie Bob Alice 21

Mid-Term Exam (2) Date: 12/7 (Friday) p Time: 09: 00 -11: 00 p Place:

Mid-Term Exam (2) Date: 12/7 (Friday) p Time: 09: 00 -11: 00 p Place: H-103 p Scope: p n n p Chapter 2, 3, 4, 5 Math functions String functions File I/O functions Note: n Open book; turn off computer & mobile phone 22

Command-Line Arguments p Suppose you developed a program “number. cpp”, which can open a

Command-Line Arguments p Suppose you developed a program “number. cpp”, which can open a file and print out each line with a line number in front of it. Alice Bob Charlie Dennis p Alice Bob Charlie Dennis You want to compile it to “number. exe”, so that you can run it as a utility. n n p 1 2 3 4 number myfile. txt number height. txt This means that the program must be able to get “input” from the command line. 23

Exercise p word_count() n n 2 1 1 4 6 4 2 12 35

Exercise p word_count() n n 2 1 1 4 6 4 2 12 35 book. txt 26 sample. txt 11 test. txt 72 total 24

Homework p Given a history file of TETRIS. Write a replay() function to replay

Homework p Given a history file of TETRIS. Write a replay() function to replay it. 25

Binary Files p WAVEIO 26

Binary Files p WAVEIO 26

fseek p int fseek ( FILE * stream, long int offset, int origin )

fseek p int fseek ( FILE * stream, long int offset, int origin ) p The function fseek() sets the file position data for the given stream. 27

fseek (cont. ) /* fseek example */ #include <stdio. h> int main () {

fseek (cont. ) /* fseek example */ #include <stdio. h> int main () { FILE * p. File; p. File = fopen ( "example. txt" , "w" ); fputs ( "This is an apple. " , p. File ); fseek ( p. File , 9 , SEEK_SET ); fputs ( " sam" , p. File ); fclose ( p. File ); return 0; } 28

fwrite p size_t fwrite ( const void * ptr, size_t size, size_t count, FILE

fwrite p size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ) p The fwrite() function writes, from the array buffer, count objects of size to stream. The return value is the number of objects written. 29

fwrite (cont. ) /* fwrite example : write buffer */ #include <stdio. h> int

fwrite (cont. ) /* fwrite example : write buffer */ #include <stdio. h> int main () { FILE * p. File; char buffer[] = { 'x' , 'y' , 'z' }; p. File = fopen ( "myfile. bin" , "wb" ); fwrite (buffer , 1 , sizeof(buffer) , p. File ); fclose (p. File); return 0; } 30