C + + read and write file operation code

Source: Internet
Author: User
Tags control characters flush numeric string to file strlen

C + + read and write file operation code


Constant Value Description
Fmopenread 0 opens with read-only property
Fmopenwrite 1 opens with write-only property
Fmopenreadwrite 2 opens with read/write properties
Fmsharecompat 0 Compatible FCB mode (the assembly has the corresponding DOS function call, interested in the relevant information from the reference

)
Fmshareexclusive 16 Sharing: Open exclusively, before shutting down, others cannot access
Fmsharedenywrite 32 sharing mode: Deny Write access
Fmsharedenyread 48 sharing mode: Deny Read access
Fmsharedenynone 64 sharing: No restrictions, allow read and write
Example: int I=fileopen ("C:windowswin.ini", fmopenreadwrite|fmshareexclusive);
⑵fileclose ()
Prototype: extern PACKAGE void __fastcall fileclose (int Handle);
Function: Closes the open handle.
Parameters: Handle: Handle to close
Example: FileClose (i);
⑶fileread ()
Prototype: extern PACKAGE int __fastcall fileread (int Handle, void *buffer, int

Count);
Function: Reads a file, returns the number of bytes actually read, and the handle must first be created by FileOpen or filecreate.
Parameters: Handle: the handle to read; Buffer: Buffers for storing the read data; Count: Number of bytes to read
Example: Char str[400]; Fileread (hnd1,str,400);
⑷fileseek ()
Prototype: extern PACKAGE int __fastcall fileseek (int Handle, int Offset, int

Origin);
Function: Move the file read pointer, successfully return the location of the file pointer, failure return-1
Parameters: Handle: Associated handle; offset: the amount of movement; Orgin: Moving datum, 0 = File header, 1 = current

Position, 2 = end of file.
Example: ShowMessage (FileSeek (hnd1,0,2));//length of file obtained
⑸filewrite ()
Prototype: extern PACKAGE int __fastcall filewrite (int Handle, const void *buffer,

int Count);
Function: Writes a file, returns the actual number of bytes written, and the handle must first be created by FileOpen or filecreate.
Parameters: Handle: The handle to be written; Buffer: Storing buffers for writing data; Count: Number of bytes to write
Example: Char str[]= "I love You"; FileWrite (Hnd1,str,strlen (str));
⑹filecreate ()
Prototype: extern PACKAGE int __fastcall filecreate (const ansistring FileName);
Function: Create a file. Returns its handle successfully or returns-1
Parameters: FileName: filename to create
Example: if (! FileExists ("KC.") C ")) hnd1=filecreate (" KC. ") C ");

C + + supports the input and output of files through several classes:

Ofstream: File class for write operations (output) (extended by Ostream)
Ifstream: File class for read operations (input) (extended by IStream)
FStream: A file class that can be read and write simultaneously (extended by iostream)


Open file (open a file)
The first action on an object of these classes is usually to associate it with a real file, which means

Open a file. A file that is opened is represented in a program by a stream object (one of these classes

instance, and any input-output operation on this stream object is actually an operation on the file.

To open a file through a Stream object, we use its member function open ():

void Open (const char * filename, openmode mode);
Here filename is a string representing the name of the file to be opened, mode is a combination of the following markers:

Ios::in open files for input (read)
Ios::out Open file for output (write)
Ios::ate initial Position: End of File
Ios::app all outputs are appended to the end of the file
Ios::trunc Delete the file if it already exists
Ios::binary binary mode

These identifiers can be combined in the middle with the "or" operator (|) Interval. For example, if we want to have the binary side

Type to open the file "Example.bin" to write some data, we can invoke the member function open () in the following way

To achieve:

Ofstream file;
File.Open ("Example.bin", Ios::out | ios::app | ios::binary);
Ofstream, Ifstream and fstream all of these classes have member function open that contains a default open file

Methods, the default methods for these three classes are different:

Default method for class parameters
Ofstream Ios::out | Ios::trunc
Ifstream ios::in
FStream Ios::in | Ios::out

The default value is applied only if the function is invoked without declaring the method arguments. If the function is invoked, the sound

Clear any parameters, the default values will be completely overwritten without combining with the invocation parameters.

Because the first operation of the Ifstream and FStream objects is usually the opening of the file for class Ofstream,

These classes have a constructor that can call the open function directly and have the same arguments. So that we can pass

The same definition objects and open files are done in the following ways:

Ofstream file ("Example.bin", Ios::out | ios::app | ios::binary);
Both of the ways to open the file are correct.

You can check whether a file has been successfully opened by calling the member function Is_open ():

BOOL Is_open ();
It returns a Boolean (bool) value that is true (true) to represent that the file has been opened successfully and false (false) instead.

Close file (Closing a files)
When the file read and write operation is complete, we must close the file to make the file accessible again. Closing a file requires

Call the member function close (), which is responsible for emitting data from the cache and closing the file. It's a simple format:

void Close ();
Once this function is invoked, the original stream object (Stream objects) can be used to open other files, which

The file can also be accessed again by all other processes (process).

To prevent the stream object from being destroyed, the open file is also contacted, and the destructor (destructor) will automatically call the shutdown function

Close

Text document (text mode files)
Class Ofstream, Ifstream and FStream are derived from Ostream, IStream and iostream respectively.

This is why FStream objects can access data using members of their parent class.

In general, we will use these classes to enter the same member functions (CIN and cout) that interact with the console (console)

Line input and output. As shown in the following example, we use the overloaded insert operator <<:

Writing on a text file #include <fiostream.h> int main () {

Ofstream examplefile ("Example.txt"); if (Examplefile.is_open ()) {

Examplefile << "This is a LINE.N"; Examplefile << "This is

Another LINE.N ";        Examplefile.close ();    return 0; }

File Example.txt
This is a line.
This is another line.

Reading data from a file can also be used in the same way as CIN:

Reading a text file #include <iostream.h> #include <fstream.h>

#include <stdlib.h> int main () {char buffer[256]; Ifstream

Examplefile ("Example.txt"); if (! Examplefile.is_open ()) {cout <<

"Error opening file"; Exit (1); while (! examplefile.eof ()) {

Examplefile.getline (buffer,100);        cout << buffer << Endl; }

return 0; This is a line.
This is another line.

The example above reads the contents of a text file and then prints it to the screen. Note that we have used a new

The member function is called EOF, which is inherited from the class iOS and returns True when the end of the file is reached. ifstream

Validation of status identifiers (verification of State flags)
In addition to EOF (), there are some member functions that verify the state of the stream (all return a bool return value):

Bad ()
Returns true if an error occurs during the read and write process. For example, when we want to do a file that is not open for write state

When writing, or the device we are writing to has no space left.

Fail ()
Returns true except in the same case as bad (), plus true when formatting errors, such as when you want to read

Into an integer, and when a letter is obtained.

EOF ()
Returns true if the read file reaches the end of the file.

Good ()
This is most common: This function returns False if any of the above functions return true.

To reset the status flags checked by the above member function, you can use the member function clear () with no parameters.

Gets and sets the stream pointer (get and put stream pointers)
All input/output stream objects (I/O streams objects) have at least one stream pointer:

Ifstream, like IStream, has a pointer called get pointer that points to the next element that will be read.
Ofstream, like Ostream, has a pointer put pointer that points to the location where the next element is written.
FStream, similar to iostream, while inheriting get and put
We can read or configure these stream pointers to the read and write locations in the stream by using the following member functions:

Tellg () and TELLP ()
These two member functions return the Pos_type type value (according to the ansi-c++ standard) without passing in the argument, which is an integer

Number that represents the position of the current get stream pointer (with TELLG) or the position of the put stream pointer (with TELLP).

SEEKG () and SEEKP ()
This pair of functions is used to change the position of the stream pointer get and put respectively. Two functions are overloaded with two different prototypes:

SEEKG (pos_type position);
SEEKP (pos_type position);
Using this prototype, the stream pointer is changed to point to an absolute position that is calculated from the start of the file. Required parameter types to be passed in

Same as the return value type of the function Tellg and TELLP.

SEEKG (off_type offset, seekdir direction);
SEEKP (off_type offset, seekdir direction);
Using this prototype, you can specify a displacement (offset) that a specific pointer starts to compute by the parameter direction.

。 It can be:

Ios::beg the displacement calculated from the start position of the stream
Ios::cur the displacement calculated from the current position of the stream pointer
Ios::end the displacement calculated from the end of the stream

Flow pointer get and put values to the text file and the binary (binary file) calculation methods are

is different because some special characters in text-mode files may be modified. For this reason, it is recommended that the text

File mode open files always use the first prototype of SEEKG and SEEKP, and do not TELLG or TELLP

The return value is modified. For binary files, you can use these functions arbitrarily, and there should be no unexpected behavior.

Health

The following examples use these functions to obtain the size of a binary file:

Obtaining file size #include <iostream.h> #include <fstream.h>

const char * filename = "example.txt"; int main () {long l,m;

Ifstream file (filename, ios::in|ios::binary); L = File.tellg ();

FILE.SEEKG (0, Ios::end);        m = File.tellg (); File.close ();

cout << "size of" << filename; cout << "is" << (m-l) << "BYTES.N";

return 0; The size of Example.txt is bytes.


Binaries (Binary files)
In binary files, using << and >>, and functions (such as getline) to enter and output data, nothing

The practical meaning, though they are grammatically compliant.

The file stream includes two member functions that are specially designed for sequential read-write data: Write and read. First function (write)

is a member function of the ostream, which is inherited by Ofstream. And read is a member function of IStream,

Be inherited by the ifstream. The FStream object of the class has both functions. Their prototypes are:

Write (char * buffer, streamsize size);
Read (char * buffer, streamsize size);
Here the buffer is a memory address that is used to store or read the data. The parameter size is an integer value that represents the

The number of characters read or written in cache (buffer).

Reading binary file #include <iostream> #include <fstream.h>

const char * filename = "example.txt"; int main () {char * buffer;

Long size; Ifstream file (filename, ios::in|ios::binary|ios::ate);

Size = File.tellg ();        FILE.SEEKG (0, Ios::beg); Buffer = new

char [size];        File.read (buffer, size); File.close ();

cout << "The complete file is in a buffer"; delete[] buffer;

return 0; The complete file is in a buffer


Caching and synchronization (buffers and synchronization)
When we operate on file streams, they are associated with a streambuf type of cache (buffer).

This cache (buffer) is actually a piece of memory space, as a medium for streaming (stream) and physical files. For example, for

An output stream, which is invoked each time a member function is put (writing a single character), which is not written directly to the output

In the physical file that corresponds to the stream, but is first inserted into the cache (buffer) of the stream.

When the cache is emitted (flush), all data inside it is either written to the physical medium (if it is an output stream

), or simply erased (if it is an input stream). This process is called Synchronization (synchronization)

, it will occur in any of the following cases:

When a file is closed: All caches that have not been fully written out or read are synchronized until the file is closed.
When the cache buffer is full: The cache buffers has a certain space limit. When the cache is full, it is automatically synchronized.
The controller explicitly indicates that synchronization occurs when some specific control characters in the stream are encountered. These control characters include: Flush and

Endl
Explicitly invoke function sync (): Call member function sync () (without parameters) can cause immediate synchronization. This function returns a

int value, equal to-1 indicates that the stream has no associated cache or operation failed.
In C + +, there is a stream of this class, all I/O is based on this "flow" class, including the one we want to know

File 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 to output the string "Write Stdout" and newline characters (' n ') to

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, the

In,cin>>x;, data is read from a standard input stream of 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 use this

To manipulate files, 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
Ios::out: File opened in output mode
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, FStream has two subclasses: ifstream (input file stream) and Ofstream (OUTPU file

Stream), Ifstream opens the file by default, and Ofstream opens the file as output by default.

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, you

Defined by Ifstream, and if you want to open it as output, use Ofstream to define it, and if you want to do it in the input/output way

To open it, define it with FStream.

Second, close the document
The open files must be closed after use, and FStream provides the member function close () to complete this operation, such as:

File1.close () to close the file1 connected file.

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 analysis

, and for binary read to be more complicated, the next to the detailed introduction of these 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

Open as input, file2 open 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 has the following

A few

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<

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, as

File1.put (' C '): 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, and the result

Saved in reference CH, if the end of the file, returns the null character. such as File2.get (x), which means reading a character from a file

, and Fu Paocun the read words in X.

Another prototype of the overloaded form is: int get (), which returns a character from the stream, if the end of the file is reached,

Returns EOF, such as X=file2.get (), which is the same as the previous example function.

Another form of the prototype is: Ifstream &get (char *buf,int num,char delim= ' n ');

Reads the character into an array pointed to by BUF until it reads num characters or encounters characters specified by Delim, such as

If you do not use Delim This parameter, the default value will be used to line up the ' n '. For example:

File2.get (str1,127, ' a '); reads the character from the file to the string str1, when it encounters the character ' A ' or reads 127

A character is terminated.

③ 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 into the cache pointed to by BUF, if the NUM characters are not read yet

At the end of the file, you can use the member function int gcount () to get the number of characters actually read, and write () from the BUF

Point to the cache write num characters to the file, it is noteworthy that the type of cache is unsigned char *, sometimes can

can 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. 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 reading point

Needle, 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 execution loses

When you enter or output, the corresponding pointer automatically changes. Therefore, the file location of C + + is divided into the location of read and write location,

The member functions that are expected are SEEKG () and SEEKP (), SEEKG () are set to read locations, and SEEKP are set to write locations. Their most

The general form is as follows:

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

Streamoff is defined in iostream.h and defines the maximum value that offsets offset can achieve, Seek_dir table

Shows the base position of the move, which 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 generally used in binary files, because the text file can be interpreted by the system to the character and may be the expected value

Different.

Cases:

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

Read each character (Chinese character) in a TXT file (the file will be very large, there are several megabytes) by one reading (read by line)

Line), and then write it again (line by row) after the operation ....

while (1)
{
if (fgets (OUTBUF,LINE,FPI) ==null)
{
Break
}//read to end of file exit loop, Outbuf take a row

Treatment of Outbuf
Treatment of Outbuf
Treatment of Outbuf

   //fprintf (FPO, "%s", outbuf); Just output one line to file
   //If output is 1 characters, use the following
     {
        fputc (OUTBUF[I],FP);
         if (outbuf[i]>127 | | outbuf[i]<0)
        {
            i++;                   //Double byte to take one more (Chinese characters to take 2 characters)
             FPUTC (OUTBUF[I],FP);
       }
   }
}

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.