Why SHOULD YOOSE FSTREAM CLASSES for FILE IO IN C ++?

xiaoxiao2021-03-06  113

The file I / O library offers several advantages over ANSI C's , including an object-oriented interface, internationalization and localization support, safety, and simpler usage. Let's take at look at how you can use this library efficiently and effectively.Introducing classesThe library includes three basic classes: ifstream, ofstream, and fstream, which represent an input file, an output file, and a combined input and output file, respectively Class ifstream supports the overloaded. >> operator Class ofstream supports the << operator Class fstream supports both << and >> operators All objects may take a filename as a constructor's argument and automatically open that file For example:.... std :: ofstream dictionary ( "myfile.txt"); The classes' destructors automatically flush the file's content and close it, so there's no risk of file corruption if you do not close the file explicitly If you do not provide a filename during. Construc Tion, You CAN Open THE LATER BY CALLING THE'S AN EXAMPLE: std :: OFSTREAM DICTIONARY; DICTIONARY.Open ("myfile.txt"); Dictionary.close (); // Explicit to Demonstrate The high-level features of the library, let's look at a concrete example. Listing A contains a program that creates an ifstream object called dictionary, opens a file called dict.txt, and prints each word in it on the screen.Consider How Simple This Program Is Compared To A Typical -based Implementation. for Starters, There's No need to check for an eof condition at each read operation. The

classes overload the! operator. If an error has occurred, the! operator evaluates as true. We take advantage of this feature to check whether the file was opened successfully after its construction. The while loop also uses this operator implicitly to check the file's status on each iteration. Finally, when the program terminates, dictionary's destructor closes the file automatically.File modesIf you do not specify explicit open modes, fstream classes use default modes. For instance, ifstream opens a file in read mode by default and sets the .. file pointer at the file's beginning Similarly, ofstream opens a file in read mode You may combine multiple flags by using the bitwise OR operator like this: ofstream logfile ( "login.dat", ios :: binary | ios :: app) .; Listing B contains a list of the open modes and file attributes versus The prestandard (which is now considered deprecated and therefore should not be used in new code) supported the ios: : NOCREATE AND IOS: : NorePlace Flags. The library doesn't support these Flags Anymore. However, this Article Shows How You Can Easily IMITATE Their FunctionAlity.

File repositioningA file object has a logical pointer that points to a certain offset within the physical file. You can position this pointer to an arbitrary location by calling the seekp () member function. This member function advances the file position by a specified offset from the Current Position. in The Following Example, The Program Advances The File's Position 10 BYTES AND THEN CALLS TELLP () To Report The New Position: OFStream Fout ("Parts.txt"); fout.seekp (10); //move 10 bytes ahead from beginningcout << "new position:" << fout.tellp (); // display 10The seekp () member function has another overloaded version, which takes a direction as a second argument For instance, this function call moves the current. File Position Two Bytes Back from The Current Position. Fout.seekp (-3, iOS :: Cur); You Can Use the Following Constants To Indicate The Direction of The File's Position: ios :: Beg // Position At File's Beginningios :: Cur // Current Position, for Example: iOS :: Cur 5ios :: End // Position A t file's endCombine read and write operationsThe classes overload the << and >> operators for all the built-in datatypes, as well as for some of the standard classes, such as std :: string and std :: complex. Listing C shows how to use these operators to perform a combined read and write operation. The program opens a file, writes two fields to it, rewinds to the file's beginning, and then reads the previously fields into time_t and std :: string objects written. Internationalization Supportone of The Novel Features of the

library is wchar_t support. Each of the classes I've discussed thus far has a wchar_t equivalent that supports files containing wchar_t data. The names of these classes are wifstream, wofstream, and wfstream. However, the C standard supports only char-oriented filenames , so these classes may take only char * arguments, regardless of their content. Listing D shows a whcar_t version of the program we saw in Listing A. Notice again how simple the migration from char-oriented I / O to wchar_t is. is a viable alternative to admittedly, is not flawless, nor does it address every need of every programmer. For example, UNIX programmers who are used to working with file descriptors rather than filenames would find < fstream> classes rather frustrating, since there's no standard means for converting descriptors to filenames and vice versa. Similarly, the lack of support for wchar_t filenames could be problematic in certain localized environments. Still, if your aim is t O Use as an alternative to , you will find this it's more intuitive and robust and offten requires fewer Keystrokes Than ITS C equivalent.listing a # include

#include

#include

#include

Using namespace std;

int main ()

{String S; ifstream Dictionary ("Dict.txt"); if (! Dictionary) // WERE THERE ANY ERRORS ON OPENING? EXIT (-1); while (Dictionary >> s) cout << S << '/ n "

}

Listing B iOS :: App // Append

ios :: ate // Open and seek to file's end

ios :: binary // binary mode I / o (as opposed to text mode)

ios :: in // Open for Read

ios :: OUT // Open for WRITE

ios :: trunc // truncate file to 0 longthlisting c #include

#include

#include

int main ()

{TIME_T login; std :: string user; fstream logfile ("log.dat"); // read write logfile << Time (0) << "USER205" << '/ n'; // Write a new record Logfile.seek (ios :: beg); // rebind logfile >> login >> user; // read previously Written VALUES

}

Listing D

#include

#include

#include

#include

Using namespace std;

int main ()

{Wstring s; // wchar_t strings Wifstream Dictionary ("Chinese_dict.utf"); // Unicode File if (! Dictionary) // WERE The Any Errors ON OPENING? EXIT (-1); // Wcout Supports Wide Characters While Dictionary >> s) wcout << s << '/ n';}

转载请注明原文地址:https://www.9cbs.com/read-101870.html

New Post(0)