280 likes | 399 Vues
Chap2. Fundamental File Processing Operations. Chapter Objectives. Describe the process of linking a logical file within a program to an actual physical file or device Describe the procedures used to create, open, and close files Introduce the C++ input and output classes
E N D
Chapter Objectives • Describe the process of linking a logical file within a program to an actual physical file or device • Describe the procedures used to create, open, and close files • Introduce the C++ input and output classes • Explain the use of overloading in C++ • Describe the procedures used for reading from and writing to files • Introduce the concept of position within a file and describe procedures for seeking different positions • Provide an introduction to the organization of the UNIX file systems • Present the UNIX view of a file, and describe UNIX file operations and commands based on this view
Contents 2.1 Physical files and Logical files 2.2 Opening files 2.3 Closing files 2.4 Reading and Writing 2.5 Seeking 2.6 UNIX directory structure 2.7 Physical and Logical files 2.8 File-related header files 2.9 UNIX file system commands
Physical files and Logical files • Physical file • a file that actually exists on secondary storage • a file as known by OS and that appears in file directory • Logical file • a file as seen by program • allow program to describe operations to be performed on file not knowing what physical file will be used
Connections bet. Physical files and Logical files • Main frame era: by Job Control Language • Unix and DOS era: by the instructions within the program (O/S system calls or parts of PLs) • ex) select inp_file assign to “myfile.dat” • inp_file: logical file, myfile.dat: physical file
Opening files • Two options • open existing file • create new file, deleting any existing contents in the physical file • ex) fd = open(filename, flags [pmode]); • fd: file descriptor • filename: physical file name • flags: O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY • pmode: in O_CREAT, pmode is required protection mode
Opening files: Example • Pmode = 0751 = 111 101 001 {owner, group, world × read, write, execute} • fd = open(fname, O_RDWR|O_CREAT,0751) • fd = open(fname,O_RDWR|O_CREAT|O_TRUC,0751) • fd = open(fname, O_RDWR|O_CREAT|O_EXCL,0751)
Closing files • Files are closed automatically by the OS when a program terminate normally • CLOSE statement is needed only as protection against data loss in the event of program interruption and to free up logical filenames for reuse • ex) close(fd); (fd : file descriptor)
Reading & Writing(1) • Input / Output operation • low-level system call (Unix) • read(Source_file, Destination_addr, Size) • write(Destination_file, Source_addr, Size) • C streams (in stdio.h) • file = fopen(filename, type); • fread, fget, fwrite, fput, fscanf, fprintf
Reading & Writing(2) • Input/Output operations(cont’d) • C++ stream classes (in iostream.h, fstream.h) • fstream() • fstream(char *fname, int mode); • int open(char *fname, int mode); • int read(unsigned char *dest_addr, int size); • int write(unsigned char *source_addr, int size); • modes: ios::in, ios::out, ios::nocreate, ios::noreplace, ios::binary
The File Listing Program Using C Streams // list.cpp // program using C streams to read characters from a // file and write them to the terminal screen #include <stdio.h> main() { char ch; FILE * file; // pointer to file descriptor char filename[20]; printf(“Enter the name of the file : “); gets(filename); file = fopen(filename, “r”); while (fread(&ch, 1, 1, file) != 0) fwrite(&ch, 1, 1, stdout); fclose(file); }
The File Listing Program Using C++ Stream Classes // listcpp.cpp // list contents of file using C++ stream classes #include <iostream> #include <fstream> using namespace std; Int main() { char ch; fstream file; // declare unattached fstream char filename[20]; cout << “Enter the name of the file : “; cout.flush(); // force output cin >> filename; file.open(filename, ios::in); file.unsetf(ios::skipws); // include write space in read while(1){ file >> ch; if (file.fail()) break; cout << ch; } file.close(); return 0; }
Reading & Writing(3) • Detecting the end of file • In C, fread() returns zero when reached the end of file • In C++, fstream::fail() return true if the previous operation on the stream failed • In Ada, end_of_file function is called before trying to read the next byte
Seeking • moving directly to a certain position in a file • lseek(Source_file, Offset, Origin) in Unix • Offset - the pointer moved from the start of the source_file • File is viewed as an array of byte in C • pos = fseek(file, byte_offset, origin) • origin – 0, 1, 2 (SEEK_SET, SEEK_CUR, SEEK_END) • In C++, An object of type fstream has two pointers • seekg(byte_offset, origin) moves the get pointer • seekp(byte_offset, origin) moves the put pointer • origin – ios::beg, ios::cur, ios::end • file.seekg(373, ios::beg), file.seekp(373, ios::beg)
UNIX Directory Structure • UNIX file system : tree organization • File : identified by its absolute value • ex) /usr/mydir/addr • ‘.’ current directory, ‘..’ the parent of ‘.’ / (root) bin usr usr6 dev mydir bin lib lib console kbd TAPE adb cc yacc libdf.a DF addr libc.a libm.a
Physical and Logical files in UNIX • UNIX views both physical devices and disk files as file. • ex) Keyboard(STDIN), Console(STDOUT), Error-file(STDERR) • I/O redirection, pipes • Shortcuts for switching between standard I/O and regular file I/O • ex) list > myfile /* I/O redirection */ • ex) program1 | program2 /* pipe */
Unix File System • File-related header files • /usr/include • In C, stdio.h • In C++, iostream and fstream • In Unix, fcntl.h and file.h • Unix file system commands • cat, tail, cp, mv, rm • chmod, ls, mkdir, rmdir
File I/O in C • Low-level I/O • UNIX system calls • fd1 = open(filename1, rwmode); • fd2 = open(filename2, rwmode); • read(fd1, buf, n); • write(fd2, buf, n); • lseek(fd1, offset, origin); • close(fd1); close(fd2);
<stdio.h> • fp = fopen(s, mode) /* open file s; mode “r”, “w”, “a” for read, write, append (returns NULL for error) */ • c = getc(fp) /* get character; getchar() is getc(stdin) */ • putc(c, fp) /* put character; putchar(c) is putc(c, stdout) */ • ungetc(c, fp) /* put character back on input file fp; at most 1 char can be pushed back at one time */ • scanf(fmt, a1, ....) /* read characters from stdin into a1, ... according to fmt. Each ai must be Sa pointer. Returns EOF or number of fields converted */ • fscanf(fp, .....) /* read from file fp */ • printf(fmt, a1, ....) /* format a1, ... according to fmt, print on stdout */ • fprintf(fp, ....) /* print .... on file fp */ • fgets(s, n, fp) /* read at most n characters into s from fp. Returns NULL at end of file */ • fputs(s, fp) /* print string s on file fp */ • fflush(fp) /* flush any buffered output on file fp */ • fclose(fp) /* close file fp */
File I/O in C++ • #include <fstream.h> • File Stream: fstream, ifstream, ofstream • ex) ifstream f1(“input.fil”); • ofstream f2(“output.fil”, ios::out|ios::nocreat); • fstream f3(“inout.fil”, ios::in|ios::out); • f1.get(ch); f1.eof(); f2.put(ch); f2.bad(); • f1.seekg(); f2.seekp(); • f3.close();
<iostream> class ios class istream: virtual public ios class ostream: virtual public ios class iostream: public istream, public ostream class hierarchy
Copy program in C++(1) #include <iostream> #include <fstream> using namespace std; void error(char *s, char *s2 = ““){ cerr << s << ‘ ‘ << s2 << ‘\n’; exit(1); } int main(int argc, char *argv[]) { if( argc != 3) error(“wrong number of arguments”); ifstream src(argv[1]); //input file stream if (!src) error(“cannot open input file”, argv[1]);
Copy program in C++(2) ofstream dest(argv[2]); //output file stream if(!dest) error(“cannot open output file”, argv[2]); char ch; while( src.get(ch) ) dest.put(ch); if(!src.eof() || dest.bad()) error(“something strange happened”); return 0; }
File Functions • File functions we will develop from the primitive operations • Add - add a new record to a file • Delete - remove a record from a file • Read all records in key order • Read a record with specific key value • Update a record in a file • File reorganization