C + + standard library io__c++

Source: Internet
Author: User
Tags bitwise

iostream Library of C + + standard library learning notes (i) Introduction and Istream,ostream classes of iostream libraries and Cin,cout objects

The standard input Output library of C language is stdio.h is a function library rather than a class library.
This includes our most commonly used scanf printf, which are independent global functions because the C language does not support classes.

C + + standard input Output library iostream is a class library, organized in the form of classes, using the class in the library to reference the namespace first: using namespace std;
The most commonly used are CIN and cout, both of which are objects, CIN is the object of the IStream class, cout is the object of the Ostream class, and the input cin>> and output cout<< in the left << and right Shift > > are the operator overloads of the IStream class and the Ostream class respectively.

There are 3 standard stream objects created in the iostream library:
1 CIN represents the standard input of the IStream object, and CIN allows us to read data from the device.
The 2 cout represents the standard output of the Ostream object, cout allows us to write data to the device.
3 Cerr The Ostream object that represents the standard error, Cerr is the place to export program error messages, and can only write data to the screen device.

The standard stream objects have default devices:
cout << data; cout The default device is the display buffer.
CIN >> data; CIN The default device is the keyboard buffer.

The iostream library consists of the following libraries: FStream, Iomainip, iOS, IOSFWD, iostream, IStream, Ostream, Sstream, Streambuf, Strstream.
IStream is used to access the operating system's input stream, ostream accesses the operating system's output stream, iostream inherits the two classes at the same time.

In the Ostream class, many left-shift << operators are overloaded, and overloads are made for each of the basic data types, such as
&ostream operator<< (ostream &temp, int source);
&ostream operator<< (ostream &temp, char source);
&ostream operator<< (ostream &temp, char* source);
Since the data types returned by the above overloads are ostream references, ostream can also be used as the left value, so cout<< "abc" <<endl<<123;

Also in the IStream class, many of the right shift >> operators are overloaded, and overloads are made for each of the basic data types, such as
&istream operator>> (IStream &temp,int source);
&istream operator>> (IStream &temp,char source);

Above is the terminal standard input input output, is the General PC computer Keyboard and the monitor input output.

Link Address

Learning notes for iostream Library of C + + standard library (ii) use of FStream libraries and Ofstream classes

iostream library not only supports the input and output of terminal equipment, but also supports the input and output of the file, and the input and output class declaration of the file in the FStream header file, three classes are responsible for the input and output of the file.

1) Ifstream class: Derived from the IStream class.
2) Ofstream class: Derived from the Ostream class.
3) FStream class: Derived from the Iostream class.

Because the input and output of the file is different from the input and output of the keyboard and mouse, the general PC has only one keyboard device, so the iostream library declares an object cin of the IStream class, this object is responsible for obtaining data from the keyboard, and the file device is in the system by many, So inside the iostream library, you can create a Ifstream object for the machine and a Ofstream object that is responsible for writing the data for each file. So we need to create a ifstream or Ostream class object for a file to read or write to.

The default constructor for the Ofstream class is as follows: Ofstream::ofstream (const char * filename, int mode = iOS:: out, int openport = Fileb Uf::openport);

FileName is the name of the file you want to open.
Mode is the way to open,
Openport is the property that opens the file.

Mode can be set in the following ways:
Ios::app Open in Append mode
Ios::ate file Open and navigate to end of file
Ios::binary opens the file in binary mode, which is opened as text by default
Ios::in file opens in read (input) mode
Ios::out file opens in write (output) mode
Ios::trunc If the file exists, empty the file.
The above attributes are used "|" (bitwise OR) connected.

The Openprot properties are as follows:
0 Common Documents
1 read-Only files
2 implied file
4 System files
The above attributes can be organized in addition or bitwise OR, for example, 1|2 and 3 represent both read-only and implied files.

You can leave the third argument in the Windows operating system, and if you add the third argument, the third argument is how you want to open the file, that is, whether the other process can read or write to the file when you open it.
The shared mode parameter can be the following value:
0x10//_SH_DENYRW denies read and write access to the file
0x20//_SH_DENYWR denies write access to the file
0x30//_sh_denyrd denies read access to the file.
0x40//_sh_denyno permits read and write access
Other values will be reported as "Invalid sharing flag" errors.  Ofstream hfile ("C:\\1.txt", iOS:: Out, _SH_DENYRW); _SH_DENYRW is deny read and write

if (! hfile)//If the file could open, hfile is a handle, or else is zero
{
cout << "Write fail!" << Endl;
cout << Access is denies,maybe The file is Readonlys,or use Deny read opened to other process. "<< Endl;
}
Else
{
Hfile << "by Coderlee writes";
cout << "Write success!" << Endl;
}
Hfile.close (); Opened file need close.

The above is the case code to write files, first open the file, and then judge whether 0, if it is 0, then prompts write fail otherwise write the file, prompted write success.

Ofstream is from memory to hard disk, Ifstream is from hard disk to memory, in fact, the so-called flow buffer is memory space;

In C + +, there is a stream this class, all I/O is based on this "flow" class, including the file we want to know i/o,stream this class has two important operators:

1. Insert (< <)
Output data to the stream. For example, the system has a default standard output stream (cout), usually refers to the display, so,cout< < "Write Stdout" < < ' n '; Indicates that the string "Write Stdout" and newline characters ('/n ') are exported to the standard output stream.

2, the extraction of the device (> >)
Enter data from the stream. For example, the system has a default standard input stream (CIN), usually refers to the keyboard, so,cin> > x; Is the data that reads a specified type (that is, the type of the variable x) from the standard input stream.

In C + +, the operation of the file is implemented through the subclass FStream (file stream) of the stream, so to manipulate the file in this way, you must join the header file fstream.h. The following is the operation of this type of file one by one-way.

First, open the file
In the FStream class, there is a member function open (), which is used to open the file, and its prototype is:

void Open (const char* filename,int mode,int access);

Parameters:

FileName: the filename to open
Mode: How to open a file
Access: Open a file's properties
The way you open the file is defined in class iOS (the base class for all streaming I/O classes), and the common values are as follows:

Ios::app: Open the file as an append
Ios::ate: When the file is opened and positioned at the end of the file, Ios:app contains this property
Ios::binary: Opens the file in binary mode, the default way is the text mode. The difference between the two ways is seen in the preceding text
Ios::in: File opened in input mode (file data entered into memory)
Ios::out: File opens as output (memory data output to file)
Ios::nocreate: Failed to create file, so open file does not exist
Ios::noreplace: File is not overwritten, so if the file fails when the file is opened
Ios::trunc: If the file exists, set the file length to 0
You can use the "or" to connect the above attributes, such as Ios::out|ios::binary

The properties of the open file are:

0: Normal file, open access
1: Read-only files
2: Implied file
4: System files
You can connect the above attributes with "or" or "+", such as 3 or 1|2 to open the file with read-only and suppressed attributes.

For example: Open a file in binary input C:/config.sys
FStream file1;
File1.open ("C://config.sys", ios::binary|ios::in,0);

If the open function has only one argument for the file name, it is opened with a read/write normal file, that is:
File1.open ("C://config.sys"); < => File1.open ("C://config.sys", ios::in|ios::out,0);

In addition, FStream has the same constructor as open (), and for the above example, the file can be opened at the time of the definition:
FStream file1 ("C://config.sys");

Specifically, the FStream has two subclasses: ifstream (input file stream) and Ofstream (OUTPU file stream), Ifstream opens the file by default as input, Instead, the Ofstream opens the file by default in output mode.
Ifstream file2 ("C://pdos.def"); Open File as input
Ofstream file3 ("c://x.123"); To open a file in output mode

So, in practical applications, depending on the needs, choose a different class to define: If you want to open it as input, use Ifstream to define it, and if you want to open it as output, use Ofstream to define it, and if you want to open it in the input/output mode, use FStream to define it.

Second, close the document
The open files must be closed after use, FStream provides the member function close () to complete this operation, such as: File1.close (); Close the file that file1 connected to.

Iii. Reading and writing documents
Read and write files are divided into text files and binary file reading, for text file reading is relatively simple, with the insertion and the extraction device can be, and for binary read more complex, the next to the detailed introduction of the two ways

1. Reading and writing of text files
Text files are simple to read and write: Use the Insert (< <) to output to the file, and use the Extract (> >) to enter from the file. Suppose File1 is opened as input, and file2 is opened with output. Examples are as follows:

file2< < "I Love You"; Write a string to the file "I Love You"
int i;
file1> > i; Enter an integer value from the file.

This approach also has a simple format, such as the ability to specify the output of 16, and so on, the specific format of the following

operator function input/output
Dec formatted as decimal numeric data input and output
Endl output a newline character and refreshes the output of this stream.
Ends output an empty character output
Hex formatted as hexadecimal numeric data input and output
Oct format to octal numeric data input and output
setpxecision (int p) sets the precision digit output of a floating-point number

For example, to take 123 as hexadecimal output:file1< < hex< < 123; To 3.1415926 to 5-bit precision output:file1< < Setpxecision (5) < < 3.1415926.

2. Read and write binary files
①put ()
The put () function writes a character to the stream, its prototype is ofstream &put (char ch), and is simpler to use, such as File1.put (' C '); is to write a character ' C ' to the stream.

②get ()
The Get () function is more flexible and has 3 commonly used overloaded forms:

One is the form corresponding to put (): Ifstream &get (char & CH); The function is to read a character from the stream, and the result is saved in reference CH, and if the end of the file is returned, null characters. such as File2.get (x); Represents reading a character from a file and Fu Paocun the read word in X.

Another prototype of the overloaded form is: int get (); This form is a character returned from the stream, and if the end of the file is reached, EOF is returned, such as X=file2.get (); And the previous example function is the same.

Another form of the prototype is: Ifstream &get (char *buf,int num,char delim= '/n '), which reads the character into the array pointed to by BUF until the NUM character is read or the character specified by the Delim is encountered. If you do not use the Delim parameter, the default value of the newline character '/n ' is used. For example:

File2.get (str1,127, ' A '); Reads the character from the file to the string str1 and terminates when the character ' A ' is encountered or 127 characters are read.

③ read and write data blocks
To read and write binary blocks of data, use the member function read () and write () member functions, which are prototypes as follows:

Read (unsigned char *buf,int num);
Write (const unsigned char *buf,int num);

Read () reads num characters from a file to the cache pointed to by the buf, and if the end of the file is not read into the NUM character, the member function int gcount (); To get the number of characters actually read, while write () writes NUM characters to a file from the cache pointed to by BUF, it is noteworthy that the cache type is unsigned char * and may sometimes require type conversions.

Cases:

unsigned char str1[]= "I love You";
int n[5];
Ifstream in ("xxx.xxx");
Ofstream out ("yyy.yyy");
Out.write (Str1,strlen (str1)); Write the string str1 all in the yyy.yyy
In.read ((unsigned char*) n,sizeof (n)); Reads the specified integer from the xxx.xxx, noting that type conversions
In.close (); Out.close ();

Iv. Detecting EOF
The member function EOF () is used to detect whether the end of the file is reached and returns 0 if the end of the file returns a value other than 0. The prototype is int eof ();

Example: if (in.eof ()) ShowMessage ("has reached the end of the file.") " );

V. Positioning of documents
Unlike the C file operation, the C + + I/O system manages two pointers associated with a file. One is the read pointer, which shows the position of the input operation in the file, and the other is the write pointer, the location of the next write operation. Each time the input or output is executed, the corresponding pointer changes automatically. Therefore, the file location of C + + is divided into the location of read and write position, the corresponding member function is SEEKG () and SEEKP (). SEEKG () is to set the read location, SEEKP is to set the write location. Their most common form is as follows:

IStream &SEEKG (Streamoff offset,seek_dir origin);
Ostream & SEEKP (Streamoff offset,seek_dir origin);

Streamoff is defined in iostream.h, defines the maximum value that offset offset can take, Seek_dir represents the base position of the move, and is an enumeration with the following values:

Ios::beg: Beginning of File
Ios::cur: File Current Location
Ios::end: End of File

These two functions are typically used in binary files because the text file may be different from the expected value because of the system's interpretation of the character. Cases:

FILE1.SEEKG (1234,ios::cur); Move the file's read pointer back 1234 bytes from the current position
FILE2.SEEKP (1234,ios::beg); Moves the file's write pointer back 1234 bytes from the beginning of the file

Link Address

Write a small program that reads and writes files simultaneously in a stream

string login, User;
FStream logfile ("Log.dat", Fstream::in | fstream::out | fstream::trunc);
if (!logfile)
{
Exit (-1);
}
LogFile << "Danny is Pig" << Endl; Write a new record
LogFile << "You are right" << Endl;
int off = LOGFILE.TELLP ();
LOGFILE.SEEKP (Ios::beg); Position Reset
LogFile >> login >> user; Read a previously written value

cout << Login << user << Endl;
LOGFILE.SEEKP (Off,ios::beg);
for (int i = 0; i < i++)
{
LogFile << "You are dog" << Endl;
}

In the beginning did not write the two words that were commented out, the result "you are dog" how also can not write to the document. The estimated file pointer does not know where to go. Add these two sentences before writing to restore the position of the previous written, and then write on it, the specific pointer ran to where is not very clear, have to know the details of the interior must tell me oh.

Here's a little bit of information on the Web. This article mainly discusses C + + standard I/O library, the main content for the console input and output stream, file flow, string flow.

If there are errors or omissions in the text, please point out, thank you.

Related Article

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.