Presentation is loading. Please wait.

Presentation is loading. Please wait.

File I/O.

Similar presentations


Presentation on theme: "File I/O."— Presentation transcript:

1 File I/O

2 fopen() FILE* fopen( const char* filename, const char* mode )
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).

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

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

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

6 Inspect the text file In the command window,
Change directory to the working directory For example, if your EXE file is "D:\VisualStudeio2010\Projects\test\Debug\test.exe", then run "test.exe" to generate the file "myfile.txt" in "D:\VisualStudeio2010\Projects\test\Debug\" Inspect the content by “type myfile.txt” Edit the file by “notepad myfile.txt”

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

8 fprintf() and printf()
int printf(const char * restrict format, ...); int fprintf (FILE* stream, const char * format, ... ) 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.

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

10 Format of printf() A format string, which consists of optional and required fields, has the following form: %[flags] [width] [.precision] type type 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). c – character s – string d – decimal x – hexadecimal o - octal

11 Format of printf() (cont.)
flags 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. 0 (zero-padding) - (left adjustment) + (always put a sign before a number) width specifies the minimum number of characters output (see printf Width Specification). precision specifies the number of digits to appear after the decimal point, for e and f formats. printf("%5.2f\n", 99.99); printf("%05.2f\n", 9.9); 99.99 09.90

12 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"); printf("|%10s|\n", a[i]); printf("|%-10s|\n", a[i]); return 0; } |Apple| |Banana| |Car| | Apple| | Banana| | Car| |Apple | |Banana | |Car |

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

14 fgets() char * fgets ( char * str, int num, FILE * stream );
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 ('\0') 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.

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

16 Input: scanf() and fscanf()
int scanf(const char* format, ...); int fscanf(FILE* stream, const char* format, ...); A format specification has the following form: %[*] [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.

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

18 Format String for scanf()
The format argument can contain one or more of the following: White-space characters: blank (' '); tab ('\t'); or newline ('\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 (%). 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, scanf terminates.

19 rename() int rename(const char *from, const char *to);
Change the file/directory from to be renamed as to. 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 that is, both directories or both non-directories and must reside on the same file system. 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.

20 Reference MSDN Function Reference cstdio (stdio.h) – C++ Reference Standard C I/O [C++ Reference]

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

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

23 Command-Line Arguments
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. You want to compile it to “number.exe”, so that you can run it as a utility. number myfile.txt number height.txt This means that the program must be able to get “input” from the command line. Alice Bob Charlie Dennis 1 Alice 2 Bob 3 Charlie 4 Dennis

24 Exercise word_count() 2 6 35 book.txt 1 4 26 sample.txt
test.txt total

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

26 Binary Files WAVEIO

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

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

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

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


Download ppt "File I/O."

Similar presentations


Ads by Google