How to use Ofstream--super fine. C + + file write, read out function (turn) __jquery

Source: Internet
Author: User
Tags string to file

How to use Ofstream
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. Inserting device (<<)
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 '; means "write Stdout" and newline characters (' \ n ') Output 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), which is generally referred to as the keyboard, so,cin>>x; represents data from the standard input stream that reads a specified type (that is, the type of the variable x).
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");//Open File as Output
So, in practical applications, depending on the needs, choose a different class to define: If you want to open in the input mode, it is defined with Ifstream, if you want to open it as output, use Ofstream to define, if you want to open in the input/output mode, use FStream to set

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 (), and the file1 connected file is closed.
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
The reading and writing of a text file is simple: output to the file with the insertion device (<<), and input from the file with the extract (>>). Suppose File1 is opened as input, and file2 is opened with output. Examples are as follows:
file2<< "I love You";//write String to 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 use 123 as hexadecimal output:file1< to 3.1415926 with 5-bit precision output:file1<.
2. Read and write binary files
①put ()
The put () function writes a character to the stream, and its prototype is Ofstream &put (char ch), which is also simpler to use, such as File1.put (' C '), or 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 that corresponds to put (): Ifstream &get (char &ch); The function is to read a character from the stream, the result is saved in reference CH, and if the end of the file, the null character is returned. such as File2.get (x), which means reading a character from a file and Fu Paocun the read word in X.
Another type of overloaded form is an int get (), which returns a character from the stream, and if the end of the file is reached, EOF is returned, such as X=file2.get (), and the previous example features are 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 data blocks, 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 into the cache pointed to by BUF. If the end of the file has not yet been read into the NUM character, the member function int gcount () can be used to get the number of characters actually read, and write () writes NUM characters from the cache pointed to by BUF to the file , it is worth noting that the type of cache 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 String str1 all to Yyy.yyy
In.read ((unsigned char*) n,sizeof (n));//Read the specified integer from the xxx.xxx, note type conversion
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 &AMP;SEEKG (Streamoff offset,seek_dir origin);
Ostream &AMP;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
The use of FStream

Open a file
FStream F;
F.open ("1.txt", Ios::in | ios::binary);
if (!f.is_open ())//Check that the file is open successfully
cout << "Cannot open file." << Endl;
Ios::in and ios::bianry are all int and define how the file is opened.
Ios::in-Opens the file for reading.
Ios::out-Opens the file for writing, creates a new one if it does not exist, and clears its contents if it exists.
Ios::binary-Read and write in binary bit stream mode, default is Ios::text, but it is best to specify this way of reading and writing, even if you want to read and write text. Because in Ios::text mode, the ' \ n ' character will be converted to two characters at write time: carriage return + newline (hex:0d 0A) write, and read as inverse conversion, which can easily cause unnecessary trouble. Ios::app-Opens the file at the end of the file to write, even if the SEEKP changed the write location, will still be written at the end of the file.
Ios::ate-Opens the file at the end of the file for writing, but SEEKP is valid.
Change in the position of reading and writing
F.SEEKG (0, Ios::beg); Change the read position g mean get
F.SEEKP (0, Ios::end); Change write position P mean put
The first argument is offset offset (long), and the second parameter is the position of offset relative to three values:
Ios::beg--File header ios::end--file tail ios::cur--current position

File Read and Write
Char s[50];
F.read (S, 49);
S[50] = ' the '; Note To add the string terminator yourself
char *s = "Hello";
F.write (S, strlen (s));
Add remember to close the file with F.close () after reading and writing.
Example the following program is used to delete line numbers in the source program with line numbers.
#include
#include
using namespace Std;
Defines the format of the line number to be deleted, and the following defines the type such as: #0001 line number
const int line_num_length = 5;
const char Line_num_start = ' # ';
int main (int argc, char *argv[])
{
FStream F;
char *s = NULL;
int n;
for (int i = 1; i < argc; i++) {
cout << "Processing file" << Argv[i] << "...";
F.open (Argv[i], ios::in | ios::binary);
if (!f.is_open ()) {
cout << "Cannot OPEN" << Endl;
Continue
}
F.SEEKG (0, Ios::end);
n = f.tellg (); File size
s = new char[n+1];
F.SEEKG (0, Ios::beg);
F.read (s, N);
S[n] = ' the ';
F.close ();
Using a simple judgment, encountering a line_num_start followed by a number,
You think it's a line number.
for (int j = 0; J < N; j + +) {
if (s[j] = = Line_num_start && (s[j+1] >= ' 0 ' && s[j+1] <= ' 9 ') {
for (int k = J; k < J + Line_num_length; k++)
S[k] = ';
}
}
F.open (Argv[i], ios::out | ios::binary);
if (!f.is_open ()) {
cout << "Cannot OPEN" << Endl;
Delete[] s;
Continue
}
F.write (s, N);
F.close ();
cout << "OK" << Endl;
Delete[] s;
}
return 0;
}

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.