70 likes | 240 Views
File Input/Output. Text file and binary files File Input/output File input / output functions Binary file input / output Case study. 00100111. 00010000. 1. 0. 0. 0. 0. 00100001. 00110000. 00110000. 00110000. 00110000. 00100111. 00010000. Basics about files.
E N D
File Input/Output • Text file and binary files • File Input/output • File input / output functions • Binary file input / output • Case study
00100111 00010000 1 0 0 0 0 00100001 00110000 00110000 00110000 00110000 00100111 00010000 Basics about files • A file is a sequence (or stream) of bytes. • A text file (or ASCII file) is sequence of ASCII code, i.e., each byte is the 8 bit code of a character. • A binary file contains the original binary number as stored in memory Example: suppose integer 10000 takes four bytes in memory Text file stream (convert each number digit into its ASCII code) Binary file stream (as it is in memory)
File and Devices • Files are input/output from memory to devices such as keyboard (stdin), screen (stdout), printer, secondary storage disks • Operating systems handle the transmission of data stream between memory and I/O devices. • A program uses stdio functions to communicate with operating system to read and write files. The figure is copied from http://www.iu.hio.no/~mark/CTutorial/CTutorial.html
Program, File I/O, and OS • Stdio.h contains FILE type typedef struct{ int _fd; int _cleft; int _mode; char *_nect c char *_buff; } FILE; • Other modes for fopen • “r”, “rb” • “w”, “wb” • “a”, “ab” • “r+”, “rb+” • “w+”, “wb+” • “a+”, “ab+” • The strings with b are for binary files. FILE *pt; pt = fopen(“file1”, “r”); In compiling, (1) a FILE type structure is allocated in memory for file1, (2) a pointer variable for the FILE type variable is allocated. (3) the function fopen is included, (4) the file name and access mode is passed to the fopen function When the program is running, at fopen function (5) it sends OS a request to open file1, (6) OS then searches the files in the disk If found, (7) it opens a portal and a buffer in memory for the file and passes the address of the buffer and related info of the portal to the FILE variable of file1, and returns the address of the FILE variable to pt. If not found (8) fopen returns NULL pointer to pt. fclose(pt); will make pt NULL, not pointing to the FILE variable for file1.
Write and Read Files • Function for stdin and stdout • printf is a function which write a stream (file) of bytes in memory to the screen in a specified format • scanf is a function which read a stream (file) of bytes into memory in a specified format from keyboard. • ch = getchar(); • putchar(); See code examples • Functions for any text file • fscanf(pt, “%d”, &num); • fprintf(outfilep, “Number = %d\n”, num); • ch = getc(infilep);or ch = fgetc(infilep); • putc(ch, outfilep);or fputs(ch, outfilep); • fread() • fwrite()