| // It's okay to write and play on the national day. The English is very bad. please focus on the Code. haha :) // C ++ stream-based FILE operations enable many programmers who transfer C files to select FILE * // :) In fact, the C ++ stream operation file is also very convenient. // The following example shows how to use the instance code for a file. # Pragma warning (disable: 4786) # Include <IOSTREAM> # Include <FSTREAM> # Include <string> Using namespace std; Int main () { // Using std: cout; // Using std: endl; Cout <"********************** C ++ file opration demo ********* * ************** "<endl; Cout <"using fstream or ifstream and ofstream" <endl; Cout <"fstream derive from istream and ostream, so most of method were defined in" <endl; Cout <"istream and ostream" <endl; Cout <"By the way, I like C style/" FILE */"indeed. :)" <endl; // Input file demo Cout <endl; Cout <"***** Part 1: Input file demo *****" <endl; Fstream/* ifstream */infile; // Antoher way to declare special class or function in a namespace Using std: string; String strfilename; Cout <"Input In FileName:" <endl; Cin> strfilename; Infile. open (strfilename. c_str (), ios: in/* openmode */); // Succeed? If (! Infile) { Cout <"Cannot open file:" <strfilename <endl; Return 1; } // Read a byte Char success, ch2; Infile. get (objects ); Ch2 = infile. get (); // Read a line // Get (char *, int max_size, char dimiliter) can do the same word as getline () // But get () doesn' t drop the dimiliter, // Use ignore () to drop the dimiliter (the last byte, '/N' by default) Char pszLine [1024]; Memset (pszLine ); Infile. getline (pszLine, 1024/* read count */, '/N'/* read until reach'/N '*/); // Seek function // Seekg means seek for getting use for input file Infile. seekg (0/* offsize */, ios_base: beg/* seek from ios_base: beg ios_base: cur ios_base: end */); // Read to a buffer Infile. read (pszLine, 1024 ); // Get readed size Int nReadedSize = infile. gcount (); // Tell the position also tellg () and tellp () // Tellg () before read () and tellg () after read () then you can get the readed size // Return-1 if eof () turn true Int nCurPos = infile. tellg (); // Test end? If (infile. eof ()) { Cout <"input file reach file end" <endl; } Infile. close (); // Output file demo Cout <"***** Part 2: Output file demo ******" <endl; Fstream/* ofstream */outfile; Outfile. open ("out.txt", ios: out ); If (! Outfile) { Cout <"Cannot open out file out.txt." <endl; Return 1; } // Write a byte Char chout = 'a '; Outfile. put (chout ); // Write buffer Outfile. write (pszLine, strlen (pszLine )); // Like ifstream, seekp (), tellp () Outfile. seekp (10, ios_base: beg ); Char buffer [] = "seekp and write a buffer "; Outfile. write (buffer, strlen (buffer )); NCurPos = outfile. tellp (); Outfile. close (); Return 0; } |