📄 libg++.texinfo
字号:
@{ record r; SFile recfile("mydatafile", sizeof(record), ios::in|ios::out); recfile.raw(); for (int i = 0; i < 10; ++i) // ... write some out @{ r = something(); recfile.put(&r); // use '&r' for proper coercion @} for (i = 9; i >= 0; --i) // now use them in reverse order @{ recfile[i].get(&r); do_something_with(r); @}@}@end smallexample@section The PlotFile ClassClass @code{PlotFile} is a simple derived class of @code{ofstream}that may be used to produce files in Unix plot format. Publicfunctions have names corresponding to those in the @code{plot(5)}manual entry. @section C standard I/OThere is a complete implementation of the ANSI C stdio librarythat is built on @emph{top} of the iostream facilities.Specifically, the type @code{FILE} is the same as the @code{streambuf} class.Also, the standard files are identical to the standard streams:@code{stdin == cin.rdbuf()}. This means that you don't have tosynchronize C++ output with C output. It also means that C programscan use some of the specialized sub-classes of streambuf.The stdio library (@code{libstdio++})is not normally installed, becauseof some difficulties when used with the C libraries version of stdio.The stdio library provides binary compatibility with traditionalimplementation. Unfortunately, it takes a fair amount of care to avoidduplicate definitions when linking with both @code{libstdio++}and the C library.@node Stream, Obstack, IOStream, Top@chapter The old I/O libraryWARNING: This chapter describes classes that are @emph{obsolete}.These classes are normally not available when libg++is installed normally. The sources are currently includedin the distribution, and you can configure libg++ to usethese classes instead of the new iostream classes.This is only a temporary measure; you should convert yourcode to use iostreams as soon as possible. The iostreamclasses provide some compatibility support, but it isvery incomplete (there is no longer a @code{File} class).@section File-based classes The @code{File} class supports basic IO on Unix files. Operations arebased on common C stdio library functions.@code{File} serves as the base class for istreams, ostreams, and otherderived classes. It contains the interface between the Unix stdio filelibrary and these more structured classes. Most operations are implementedas simple calls to stdio functions. @code{File} class operations are also fullycompatible with raw system file reads and writes (like the system@code{read} and @code{lseek} calls) when buffering is disabled (see below).The @code{FILE*} stdio file pointer is, however maintained as protected.Classes derived from File may only use the IO operations provided by File,which encompass essentially all stdio capabilities.The class contains four general kinds of functions: methods for binding@code{File}s to physical Unix files, basic IO methods, file and buffercontrol methods, and methods for maintaining logical and physical filestatus.Binding and related tasks are accomplished via @code{File} constructors anddestructors, and member functions @code{open, close, remove, filedesc,name, setname}.If a file name is provided in a constructor or open, it ismaintained as class variable @code{nm} and is accessiblevia @code{name}. If no name is provided, then @code{nm} remainsnull, except that @code{Files} bound to the default files stdin,stdout, and stderr are automatically given the names@code{(stdin), (stdout), (stderr)} respectively. The function @code{setname} may be used to change theinternal name of the @code{File}. This does not change the nameof the physical file bound to the File. The member function @code{close} closes a file. The@code{~File} destructor closes a file if it is open, exceptthat stdin, stdout, and stderr are flushed but left open forthe system to close on program exit since some systems mayrequire this, and on others it does not matter. @code{remove}closes the file, and then deletes it if possible by calling thesystem function to delete the file with the name provided inthe @code{nm} field.@section Basic IO@itemize @bullet@item @code{read} and @code{write} perform binary IO via stdio@code{fread} and @code{fwrite}.@item @code{get} and @code{put} for chars invoke stdio @code{getc}and @code{putc} macros.@item @code{put(const char* s)} outputs a null-terminated string viastdio @code{fputs}.@item @code{unget} and @code{putback} are synonyms. Both call stdio@code{ungetc}.@end itemize@section File Control@code{flush}, @code{seek}, @code{tell}, and @code{tell} call thecorresponding stdio functions.@code{flush(char)} and @code{fill()} call stdio @code{_flsbuf}and @code{_filbuf} respectively.@code{setbuf} is mainly useful to turn off buffering in caseswhere nonsequential binary IO is being performed. @code{raw} is asynonym for @code{setbuf(_IONBF)}. After a @code{f.raw()}, usingthe stdio functions instead of the system @code{read, write},etc., calls entails very little overhead. Moreover, these becomefully compatible with intermixed system calls (e.g.,@code{lseek(f.filedesc(), 0, 0)}). While intermixing @code{File}and system IO calls is not at all recommended, this techniquedoes allow the @code{File} class to be used in conjunction withother functions and libraries already set up to operate on filedescriptors. @code{setbuf} should be called at most once after aconstructor or open, but before any IO.@section File StatusFile status is maintained in several ways. A @code{File} may be checked for accessibility via@code{is_open()}, which returns true if the File is bound to ausable physical file, @code{readable()}, which returns true ifthe File can be read from (opened for reading, and not in a_fail state), or @code{writable()}, which returns true if theFile can be written to.@code{File} operations return their status via two means: failure andsuccess are represented via the logical state. Also, thereturn values of invoked stdio and system functions thatreturn useful numeric values (not just failure/success flags)are held in a class variable accessible via @code{iocount}.(This is useful, for example, in determining the number ofitems actually read by the @code{read} function.)Like the AT&T i/o-stream classes, but unlike the description inthe Stroustrup book, p238, @code{rdstate()} returns the bitwiseOR of @code{_eof}, @code{_fail} and @code{_bad}, not necessarilydistinct values. The functions @code{eof()}, @code{fail()},@code{bad()}, and @code{good()} can be used to test for each ofthese conditions independently.@code{_fail} becomes set for any input operation that could notread in the desired data, and for other failed operations. Aswith all Unix IO, @code{_eof} becomes true only when an inputoperations fails because of an end of file. Therefore,@code{_eof} is not immediately true after the last successfulread of a file, but only after one final read attempt. Thus, forinput operations, @code{_fail} and @code{_eof} almost alwaysbecome true at the same time. @code{bad} is set for unboundfiles, and may also be set by applications in order to communicateinput corruption. Conversely, @code{_good} is defined as 0 andis returned by @code{rdstate()} if all is well.The state may be modified via @code{clear(flag)}, which,despite its name, sets the corresponding state_value flag.@code{clear()} with no arguments resets the state to @code{_good}.@code{failif(int cond)} sets the state to @code{_fail} only if@code{cond} is true. Errors occuring during constructors and file opens also invoke thefunction @code{error}. @code{error} in turn calls a resetable errorhandling function pointed to by the non-member global variable@code{File_error_handler} only if a system error has been generated.Since @code{error} cannot tell if the current system error is actuallyresponsible for a failure, it may at times print out spurious messages.Three error handlers are provided. The default,@code{verbose_File_error_handler} calls the system function@code{perror} to print the corresponding error message on standarderror, and then returns to the caller. @code{quiet_File_error_handler}does nothing, and simply returns. @code{fatal_File_error_handler}prints the error and then aborts execution. These three handlers, or anyother user-defined error handlers can be selected via the non-memberfunction @code{set_File_error_handler}.All read and write operations communicate either logical orphysical failure by setting the @code{_fail} flag. All furtheroperations are blocked if the state is in a @code{_fail} or@code{_bad}condition. Programmers must explicitly use @code{clear()} toreset the state in order to continue IO processing aftereither a logical or physical failure. C programmers who areunfamiliar with these conventions should note that, unlikethe stdio library, @code{File} functions indicate IO success,status, or failure solely through the state, not via return values ofthe functions. The @code{void*} operator or @code{rdstate()}may be used to test success. In particular, according to c++conversion rules, the @code{void*} coercion is automaticallyapplied whenever the @code{File&} return value of any @code{File}function is tested in an @code{if} or @code{while}. Thus,for example, an easy way to copy all of stdin to stdout untileof (at which point @code{get} fails) or some error is@code{char c; while(cin.get(c) && cout.put(c));}.@ignore@section The istream and ostream classesSome of these are supported by incorporating additional,mainly virtual, functions into streambufs:@table @code@item streambuf::open([various args])attaches the streambuf to a file, if applicable@item streambuf::close()detaches the streambuf from a file, if applicable.@item streambuf::sputs(const char* s)outputs null-terminated string s in a generally faster waythan repeated @code{sputcs}.@item streambuf::sputsn(const char* s, int n)outputs the first n characters of s in a generally faster waythan repeated @code{sputcs}.@end table@end ignoreThe current version of istreams and ostreams differs significantlyfrom previous versions in order to obtain compatibility withAT&T 1.2 streams. Most code using previous versions should stillwork. However, the following features of @code{File} are notincorporated in streams (they are still present in @code{File}):@code{scan(const char* fmt...), remove(), read(), write(),setbuf(), raw()}. Additionally, the feature of previous streamsthat allowed free intermixing of stream and stdio input and outputis no longer guaranteed to always behave as desired.@node Obstack, AllocRing, Stream, Top@chapter The Obstack classThe @code{Obstack} class is a simple rewrite of the C obstack macros andfunctions provided in the GNU CC compiler source distribution. Obstacks provide a simple method of creating and maintaining a stringtable, optimized for the very frequent task of building stringscharacter-by-character, and sometimes keeping them, and sometimesnot. They seem especially useful in any parsing application. One of thetest files demonstrates usage.A brief summary:@table @code@item grow places something on the obstack without committing to wrap it up as a single entity yet.@item finish wraps up a constructed object as a single entity, and returns the pointer to its start address.@item copy places things on the obstack, and @emph{does} wrap them up.@code{copy} is always equivalent to first grow, then finish.@item free deletes something, and anything else put on the obstack since its creation.@end tableThe other functions are less commonly needed:@table @code@item blankis like grow, except it just grows the space by size unitswithout placing anything into this space@item allocis like @code{blank}, but it wraps up the object and returns its startingaddress. @item chunk_size, base, next_free, alignment_mask, size, roomreturns the appropriate class variables.@item grow_fastplaces a character on the obstack without checking if there is enough room.@item blank_fastlike @code{blank}, but without checking if there is enough room.@item shrink(int n)shrink the current chunk by n bytes.@item contains(void* addr)returns true if the Obstack holds the address addr.@end tableHere is a lightly edited version of the original C documentation:These functions operate a stack of objects. Each object starts lifesmall, and may grow to maturity. (Consider building a word syllableby syllable.) An object can move while it is growing. Once it hasbeen ``finished'' it never changes address again. So the ``top of thestack'' is typically an immature growing object, while the rest of thestack is of mature, fixed size and fixed address objects.These routines grab large chunks of memory, using the GNU C++ @code{new}operator. On occasion, they free chunks, via @code{delete}.Each independent stack is represented by a Obstack.One motivation for this package is the problem of growing char stringsin symbol tables. Unless you are a ``fascist pig with a read-only mind''[Gosper's immortal quote from HAKMEM item 154, out of context] youwould not like to put a
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -