// input.cpp // from class Thursday 24/2/2000 // input system defined as a C++ object #include #include #include #include class input { public: input(void); // two constructors, one for keyboard input, one for a file; input (char *filename); // the class/object will work exactly the same // for each once the constructor has been called. int ok(void); int endoffile(void); void close(void); char readchar(void); void unreadchar(void); char *readline(char *s, int max); char *readline(void); // two versions of readline too. This is "overloading" char *readstring(char *s, int max, char *terminators); char *readstring(char *terminators); int readint(void); const char EndOfFile=26; protected: char buffer[512]; int file; int num_in_buff, num_taken_out, at_end_of_file, allok; void refill_buffer(void); }; input::input(void) { num_in_buff=0; num_taken_out=0; file=0; // 0 is the unix file-number for standard input (usu. keyboard) at_end_of_file=0; allok=1; } input::input(char *filename) { num_in_buff=0; num_taken_out=0; file=open(filename,O_RDONLY); if (file<0) { at_end_of_file=1; allok=0; } else { at_end_of_file=0; allok=1; } } int input::ok(void) { return (allok); } int input::endoffile(void) { return (at_end_of_file); } void input::close(void) { if (file!=0) // on next line, :: is the way you refer to a global name // in this case the standard unix library function "close" // that has the same name as a class member. ::close(file); } char input::readchar(void) { if (num_taken_out>=num_in_buff) refill_buffer(); if (!allok) return EndOfFile; char answer=buffer[num_taken_out]; num_taken_out+=1; return answer; } void input::unreadchar(void) { if (num_taken_out<=0) allok=0; if (!allok) return; num_taken_out-=1; } void input::refill_buffer(void) { if (at_end_of_file || !allok) return; int n=read(file,buffer,512); if (n<=0) { at_end_of_file=1; allok=0; n=0; } num_taken_out=0; num_in_buff=n; } char *input::readline(char *s, int max) { int i; for (i=0; i' ') break; } if (c=='-') { negative=1; c=readchar(); } while (c>='0' && c<='9') { n=n*10+c-'0'; c=readchar(); } unreadchar(); if (negative) n=-n; return n; } void main(void) { input in; printf("What file would you like to see?\n"); char *filename=in.readline(); input fin(filename); if (!fin.ok()) { printf("Can't read file \"%s\"\n", filename); exit(1); } while (1) { char c=fin.readchar(); if (c==fin.EndOfFile) { printf("EOF found\n"); break; } if (!fin.ok()) break; printf("%c", c); // also make invisible characters visible: if (c<=32 || c>126) printf("[%d]",c); } fin.close(); printf("Done\n"); }