File I/O

Source: Internet
Author: User

There are several main file I/O operations:

1. File input stream Ifstream

2. File output stream Ofstream

3. File input/output stream FStream

4. How to open a file

5. Status of the file stream

6. File stream positioning: file pointer (input pointer, output pointer)

7. text files and binaries

File stream classes and file stream objects

The input output is the object of the system-specified standard device (input device is keyboard, output device is monitor). In real-world applications, disk files are often used as objects. The data is read from the disk file and the data is output to the disk file.

The input and output classes that are related to the file are defined primarily in the Fstream.h header file, which is defined in the header file as three classes, which control the various input and output operations on the file, Ifstream, Ofstream, FStream, respectively. Where the FStream class is derived from the Iostream class, the inheritance relationship between them is shown.

Since the file device is not a standard default device like the monitor screen and keyboard, it does not have a pre-defined global object like cout in the fstream.h header file, so we have to define an object of that class ourselves.

The Ifstream class, which is derived from the IStream class, is used to support input from a disk file.

The Ofstream class, which is derived from the Ostream class, is used to support output to disk files.

The FStream class, which is derived from the Iostream class, is used to support input and output to disk files.

I. Opening and closing of C + + files

Open File

The so-called open file is an image, like opening the door to enter the room activity. Opening a file means doing the necessary preparation before the file is read and written, including:

1) Associate the file stream object with the specified disk file so that the file stream flows to the specified disk file.

2) Specify how the file works, such as whether the file is an input file or an output file, an ASCII file or a binary file, and so on.

The above work can be achieved in two different ways.

1) Call the file stream member function open. Such as

Ofstream outfile; Defines the Ofstream class (output file stream Class) object outfile

Outfile.open ("F1.dat", ios::out); Associating a file stream with a F1.dat file

The 2nd line is to call the output file stream member function open open Disk File F1.dat, and specify it as the output file, the file stream object outfile will f1.dat output data to the disk file. Ios::out is a type of I/O pattern that indicates that a file is opened in the output mode. Or simply, at this point the F1.dat is an output file that receives data from the memory output.

The general form of the call member function Open is:

File Stream object. Open (disk file name, input and output mode);

The disk file name can include a path, such as "C:\new\\f1.dat", which defaults to the file under the current directory, such as the default path.

2) Specify parameters when defining a file stream object

A constructor with parameters is defined when declaring a file stream class, which contains the ability to open a disk file. Therefore, you can specify parameters when defining a file stream object and invoke the constructor of the file stream class to implement the ability to open the file. Such as

Ostream outfile ("F1.dat", ios::out); Generally more use this form, more convenient. The function is the same as the open function.

The input and output methods are defined in the iOS class, which are enumerated constants and have several options, as shown in table 13.6.

Note A few notes:
1) ios::nocreate and Ios::noreplace are not available in the new version of the I/O class library.
2) Each open file has a file pointer, the initial position of the pointer is specified by I/O, and each read and write starts at the current position of the file pointer. Each time a byte is read, the pointer moves back one byte. When the file pointer moves to the end, you will encounter the end of the file EOF (the file terminator also takes one byte, with a value of-1), and the value of the member function EOF for the stream object is a non-0 value (typically set to 1), indicating that the file is over.
3) You can use the "bitwise OR" operator "|" Combine the input and output methods as shown in the last 3 rows in table 13.6. You can also cite some of the following examples:
Ios::in | iOS:: Noreplace//Open an input file and return the open failed message if the file does not exist
Ios::app | Ios::nocreate//Open an output file, then write the data at the end of the file, and if the file does not exist, returns the information that failed to open
Ios::out l Ios::noreplace//Open a new file as an output file and return the open failed message if the file already exists
Ios::in l ios::out I ios::binary//Open a binary file, readable writable
But they cannot be combined in mutually exclusive ways, such as Ios::nocreate l ios::noreplace.
4) If the opening operation fails, the return value of the Open function is 0 (false), and if the file is opened by calling the constructor, the value of the stream object is 0. You can test the success of the open accordingly. Such as
if (Outfile.open ("F1.bat", Ios::app) ==0)
cout << "Open error";
Or
if (!outfile.open ("F1.bat", Ios::app))
cout << "Open error";

Close File

After the read-write operation on the open disk file is complete, you should close the file. Close the file with the member function. Such as
Outfile.close (); Closes the disk file associated with the output file stream
The so-called shutdown, in effect, is to remove the disk file and file stream Association, the original set of work is also invalid, so that the file stream can no longer be input or output. You can associate a file stream with another disk file, and enter or output a new file through a file stream. Such as
Outfile.open ("F2.dat", ios::app|ios::nocreate);
At this point, the file stream outfile is associated with F2.dat and specifies how the F2.dat works.

Second, C + + to ASCII file read and write operations

If the data is stored in ASCII code in every byte of the file, that is, one byte holds one character, and the file is an ASCII file (or character file). A program can read several characters from an ASCII file, or it can output some characters to it.

1) Use the stream insert operator "<<" and the stream extraction operator ">>" to enter data for the output standard type. The "<<" and ">>" KFC are overloaded in iostream as input outputs of standard types that can be used for Ostream and IStream class objects. Since Ifstream and Ofstream are derived classes of the Ostream and IStream classes respectively, they inherit the common overloaded functions from the Ostream and IStream classes, so in operations on disk files, you can insert operators by file stream objects and streams "< < and stream extraction operator >> implements read and write to disk files, as with Cin, cout and <<, >> Read and write to standard devices.

2) Use the file stream's put, get, geiline, and other member functions for character input and output: Use the C + + Stream member function put output single character, C + + get () function read into a character and C + + getline () function read a line of characters.

Case 1: Write file, then read file # include <iostream>using namespace std; #include "fstream" int main92 () {char Filename[80];char Buffer[255];cout << "Please enter a file name:"; Cin >> filename;ofstream fout (filename, ios::app); Fout << " 1111111111111111111\n "; Fout <<" 22222222222222222\n ";//cin.ignore (1, ' \ n '); Cin.getline (buffer,255);  From keyboard input fout << buffer << "\ n"; Fout.close (); ifstream fin (fileName) cout << "Here's the content of the File: \ n "; Char ch;while (Fin.get (CH)) cout << ch;cout <<" \n***end of File contents.***\n "; Fin.close (); system ("pause"); return 0;}

  

Case 2

The default constructor for the Ofstream class is:

Ofstream::ofstream (Constchar *filename, int mode = Ios::out,

int penprot = Filebuf::openprot);

    • FileName: The file name to open
    • Mode: How to open a file
    • Prot: Opening properties of a file

The options table for the two parameters, mode and Openprot, are shown in the following table:

< P align= "Center" >mode property sheet

ios::app

ios::ate

file is opened and positioned to the end of the file, Ios:app contains this property

ios::binary

ios::in

ios::out

ios::trunc

Note: You can use the ' | ' Connect the above attributes, such as Ios::out|ios::binary.

Openprot property sheet

Property

Meaning

0

Normal file, open access

1

Read-only files

2

Implied file

4

System files

Note: You can use "or" or "+" to connect the above properties, such as 3 or 1|2 to open the file with read-only and implied properties.

#include <fstream> usingnamespace std; int main ()  {         ofstream myfile ("C:\\1.txt", ios::out|ios::trunc,0);         myfile<< "gd_" <<endl<< "URL:" << "https://i.cnblogs.com";         Myfile.close ()         system ("pause");

  

You can use the close member function to close a file after the file has been exhausted.

Ios::app is an append mode, it is a good habit to judge the state of files while using append mode.

#include <iostream> #include <fstream> usingnamespace std; int main ()  {         ofstream myfile ("C:\\1.txt", ios::app,0);         if (!myfile)//or write Myfile.fail ()         {                 cout<< "File open failed, the target file status may be read-only! ";                 System ("pause");                 Exit (1);         }         
Myfile.close ();

}

  

When defining Ifstream and Ofstream class objects, we can also not specify a file. You can then explicitly connect a file to a class object by using the member function open ().

#include <iostream> #include <fstream> usingnamespace std; int main ()  {         ofstream myfile;         Myfile.open ("C:\\1.txt", ios::out|ios::app,0);         if (!myfile)//or write Myfile.fail ()         {                 cout<< "file creation failed, the disk is not writable or the file is read-only!";                 System ("pause");                 Exit (1);         }
  myfile<< "gd_" <<endl<< "URL:" << "https://i.cnblogs.com";         Myfile.close ()         
}

Here's an example of how to use the Ifstream class object to read the data from a file and then output it to a standard device.

#include <iostream> #include <fstream> #include <string> usingnamespace std; int main ()  {         ifstream myfile;         Myfile.open ("C:\\1.txt", ios::in,0);         if (!myfile)         {                 cout<< "file read error";                 System ("pause");                 Exit (1);         }         char ch;         string content;         while (Myfile.get (CH))         {                 content+=ch;                 Cout.put (CH);//cout<<ch; So write is also possible         }         myfile.close ();         cout<<content;         System ("pause"); }

In the above example, using the member function get (), read the valid characters in the file, and then use the put () member function, the data in the file through the loop output to the standard device (screen), the Get () member function will be read to the end of the file when the false value, So we can use this feature as the termination condition of the while loop, and in the example we introduced a C + + style string, which is saved to the content one at a time, to use the string type and must contain the String.h header file.

 #include <iostream > 
#include <fstream>
usingnamespace std; 

Int main () {FStream myfile; Myfile.open ("C:\\1.txt", ios::out|ios::app,0); if (!myfile) {cout<< "file write error, file properties may be read-only!" <<endl; System ("pause"); Exit (1); } myfile<< "Gd_" <<endl<< "URL:" << "https://i.cnblogs.com";
Myfile.close ();
Myfile.open ("C:\\1.txt", ios::in,0); if (!myfile) {cout<< "file read error, file may be lost!" <<endl; System ("pause"); Exit (1); } char ch; while (Myfile.get (ch)) {cout.put (CH); } myfile.close (); System ("pause"); }

Since the FStream class can read and write to the file at the same time, it is important to explicitly specify the mode and Openprot parameters when the initial session is made to its object.

Third, C + + binary file read and write operations

Binary files do not hold data in ASCII code, it transfers the in-memory data storage form to disk files without conversion, so it is also called an image file of memory data. Because the information in a file is not character data, it is a binary form of information in bytes, so it is also called a byte file.

The operation of the binary file will also need to open the file, after the end of the file to close. The ios::binary is specified to be transmitted and stored in binary form when it is opened. Binary files can be both input and output files, in addition to being input or output files. This is a different place from the ASCII file.

Read and write binary files with member functions

The read and write of binary files are mainly implemented by the member functions of the IStream class read and write. The prototypes of these two member functions are
istream& Read (char *buffer,int len);
ostream& Write (const char * buffer,int len);
The character pointer buffer points to a piece of storage space in memory. Len is the number of bytes read and written. The method is called:
A. Write (p1,50);
B. Read (p2,30);
A in the first line above is the output file stream object, and the Write function writes the 50-byte contents of the character pointer P1 the address given to the disk file without conversion. In the second row, B is the input file stream object, and the Read function reads 30 bytes (or end of EOF) from the disk file associated with B, and is stored in a space referred to by the character pointer P2.

case int Main () {char filename[255] = "C:/teacher.dat"; ofstream fout (Filename,ios::binary); if (!fout) {cout << " Unable to open ' << fileName << ' for writing.\n '; return (1);} Teacher T1 (31, "31"); Teacher T2 (+), Fout.write ((char *) &t1,sizeof Teacher); Fout.write ((char *) &t2,sizeof Teacher); Fout.close (); cout << "Save the object to a binary file successfully!" << endl;ifstream fin (filename,ios::binary); if (!fin) {cout << " Unable to open ' << fileName << ' for reading.\n '; return (1);} Teacher tmp ("+"); Fin.read ((char *) &tmp,sizeof Teacher); Tmp.printt (); Fin.read ((char *) &tmp,sizeof Teacher); Tmp.printt (); System ("pause"); return 0;}

Practice

1 programming implements the following data input/output:

(1) output an integer in left-aligned mode with a field width of 12.

(2) in eight decimal, hexadecimal input/output integer.

(3) Implement the index format of floating-point number and the input/output of fixed-point format, and specify the precision.

(4) The string is read into the character array variable, from the keyboard input, the input string is required to read all the space, the end of the carriage return.

(5) The above requirements with the flow member functions and operators to do it again.

2 Write a program that merges two files into one file.

3 Write a program to count the number of words and the number of lines in an English article.

4 Write a program that adds a line number and a space to each line of the C + + source program.

4.5 Write a program, output ASCII code value from 20 to 127 ASCII code character, in the format of 10 per line.

First question iOS class member function implementation #include<iostream> #include <iomanip>using namespace Std;int main () {long a=234;double b= 2345.67890;char C[100];cout.fill (' * '); Cout.flags (ios_base::left); cout.width Cout.fill (' * '); Cout.flags (ios::right); Cout.width (n); Cout<<a<<endl;cout.flags (Ios.hex);cout< <234<< ' \ t '; Cout.flags (ios.dec);cout<<234<< ' \ t '; Cout.flags (IOS.OCT);cout<<234< <endl;cout.flags (ios::scientific);cout<<b<< ' \ t '; Cout.flags (ios::fixed);cout<<b<< Endl;cin.get (c,99); Cout<<c<<endl;return 0;} The operator implements #include<iostream> #include <iomanip>using namespace Std;int main () {long a=234;double b=2345.67890; Char C[100];cout<<setfill (' * '); COUT&LT;&LT;LEFT&LT;&LT;SETW (<<a<<endl;cout<<right) &LT;&LT;SETW <<a<<endl;cout<

Second question #include<iostream> #include <fstream>using namespace Std;int main () {int I=1;char c[1000];ifstream Ifile1 ("D:\\1.cpp"); Ifstream ifile2 ("D:\\2.cpp"); Ofstream ofile ("D:\\3.cpp"); while (!ifile1.eof ()) {Ifile1.getline (c,999); Ofile<<c<<endl;} while (!ifile2.eof ()) {ifile2.getline (c,999); Ofile<<c<<endl;} Ifile1.close (); Ifile2.close (); Ofile.close (); return 0;}

The third question #include<iostream> #include <fstream>using namespace Std;bool Isalph (char); int main () {Ifstream ifile (" C:\\daily.doc "), char text[1000];bool inword=false;int rows=0,words=0;int i;while (!ifile.eof ()) {Ifile.getline (text, 999) Rows++;i=0;while (text[i]!=0) {if (!isalph (Text[i])) Inword=false;else if (Isalph (text[i)) && inword== false) {words++;inword=true;} i++;}} cout<< "rows=" <<rows<<endl;cout<< "words=" <<words<<endl;ifile.close (); return 0;} BOOL Isalph (char c) {return ((c>= ' A ' && c<= ' Z ') | | (c>= ' A ' && c<= ' z '));}

 

Question Fourth #include<iostream> #include <fstream>using namespace Std;int main () {int I=1;char c[1000];ifstream ifile ("D:\\1.cpp"); Ofstream ofile ("D:\\2.cpp"); while (!ifile.eof ()) {ofile<<i++<< ":"; Ifile.getline (c,999) ; Ofile<<c<<endl;} Ifile.close (); Ofile.close (); return 0;}

  

Question Fifth #include<iostream>using namespace Std;int main () {int i,l;for (i=32;i<127;i++) {Cout<<char (i) < < ""; L++;if (l%10==0) Cout<<endl;} Cout<<endl;return 0;}

  

File I/O

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.