C + + Learning Note 4--file operations

Source: Internet
Author: User
Tags readable

"Enumeration constants in iOS"
SKIPWS: Skips whitespace reading. spaces, tabs \ t, carriage returns \ r, and newline characters \ n are collectively known as whitespace characters. The default is to set it.
Left: Aligns the output data on the right.
Right: The output data is aligned on the left.
Insternal: The display fills the entire field wide, filled with fill characters between symbols and values.
DEC: Output data in decimal.
Hex: Outputs data in hexadecimal.
Showbase: The cardinal character is displayed before the value, the octal cardinal character is 0, and the hexadecimal cardinal character is 0x.
Showpoint: Invalid number 0 in floating-point numbers that force output with decimal and fractional tails.
Uppercase: output data in uppercase.
Showpos: Displays the symbol before the value.
Scientific: Displays floating-point numbers with science and technology.
Fixed: Displays floating-point numbers with a constant number of decimal places.
Example: adding characters
#include <iostream> #include <strstream>using namespace std;int main (int argc, char* argv[]) {    char buf[] = "1002000";    int I, J;    Istrstream S1 (BUF);    S1 >> i;    Istrstream S2 (buf, 3); Read in 3 characters    S2 >> J;    cout << i + j <<endl;    return 0;}

You first open the file before you perform a file operation. There are two ways of opening a file.
(1) When creating a file stream, use the constructor to open the file, i.e. add parameters when creating the stream. The syntax structure is as follows:
< file stream class >< file stream object name > (< file name >,< Open with >)
Where file streams can be one of the fstream, Ifstream, and Ofstream. File name refers to the name of the disk file, the package


The path name of the disk file. Open mode is defined in iOS, with input mode, output mode, append method, etc.
Ios::in: Open the file with input mode, the file can only read, cannot be rewritten.
Ios::out: Open the file as output, the file can only be rewritten and cannot be read.
Ios::app: Open the file in Append mode, open the file pointer at the end of the file, can be rewritten.
Ios::ate: Opens an existing file with a file pointer pointing to the end of the file, readable and writable.
Ios::binary: Opens the file in binary mode.
Ios::trunc: Open file for write operation, if file already exists, clear data in file.
Ios::nocreate: Open a file that already exists, if the file does not exist, open failed, not created.
Ios::noreplace: Create a new file if the file already exists, open failed, do not overwrite.
Parameters can be combined with the operator ' | ' Use, for example:
Ios::in|ios::out: Open in Read and write mode, readable and writable file.
Ios::in|ios:binary: Opens the file in binary mode for read operation.
To open a file test.txt with a read path:
Ofstream outfile ("Test.txt", ios::out);
To open a file with an absolute path test.txt write:
Ofstream outfile ("C:\\Test.txt", ios::out);
(2) Open the disk file using the opening function. The syntax structure is as follows:
< file stream object name >.open (< file name >,< open mode >);
The file stream object is a file stream object that has already been defined.
Ifstream infile;
Infile.open ("Test.txt", ios::out);
After opening a file in either of two ways, the file stream object is not a 0 value if open succeeds, and if open fails,


The file stream object is 0. You can use the following statement to detect whether a file opened successfully:
void Open (const char* filename,int mode,int Prot=filebuf::openprot)
Prot determines how files are accessed, and the values are described below:
0 is indicated as a normal file.
1 is expressed as a read-only file.
2 is indicated as an implied file.
3 is represented as a system file.
Example: Creating a File
#include <iostream> #include <fstream>using namespace std;int main (int argc, char* argv[]) {    ofstream ofile;    cout << "Create file1" << Endl;    Ofile.open ("test.txt");    if (!ofile.fail ()) {        ofile << "Lasolmi" << Endl;        Ofile.close ();        cout << "Create file2" << Endl;        Ofile.open ("Test2.txt");        if (!ofile.fail ()) {            ofile << "hello.world!" <<endl;            Ofile.close ();        }    }    return 0;}

"Read and Write Files"
(1) file stream type: input stream, output stream, input/output stream.
Ifstream ifile; declares an input stream
Ofstream ofile; declares an output stream
FStream Iofile; Declaring an input/output stream
(2) file stream member function.
The Ofstream and Ifstream classes have many functions for disk file management.
Attach: Establishes a connection between an open file and a stream.
Close: Closes the file after refreshing the unsaved data.
Flush: Refreshes the stream.
Open: Opens a file and connects it to the stream.
Put: Writes a byte to the stream.
Rdbuf: Returns the Filebuf object connected to the stream.
SEEKP: Sets the position of the stream file pointer.
SetMode: Sets the stream to either binary or text mode.
TELLP: Gets the stream file pointer position.
Write: Writes a set of bytes to the stream.
(3) FStream member function.
Get (c): reads a character from a file
Getline (str,n, ' \ n '): reads a character from a file into the string str, knowing to read n-1 characters or to encounter ' \ n ' knots


Beam
Peek (): Finds the next character, but does not remove it from the file
Put (c): Writes a character to a file
Putback (c): The input is exiled back one character, but not saved
EOF (): Returns True if the read exceeds EOF
Ignore (n): Skips the next character when the argument is empty, skipping n characters
Example: the ability to read and write files using Ifstream and Ofstream objects.
#include <iostream> #include <fstream> #include <cstring>using namespace std;int main (int argc, char* Argv[]) {    char buf[128];    Ofstream ofile ("test.txt");    for (int i=0;i<5;i++) {        memset (buf,0,128);        Cin >> BUF;        Ofile << buf;    }    Ofile.close ();    Ifstream ifile ("test.txt");    while (!ifile.eof ()) {        char ch;        Ifile.get (CH);        if (!ifile.eof ()) cout << ch;    }    cout << Endl;    Ifile.close ();    return 0;}

Example: Using FStream to write data to a text file.
#include <iostream> #include <fstream>using namespace std;int main (int argc, char* argv[]) {    fstream file ("Test.txt", ios::out);    if (!file.fail ()) {        cout << "Start write" << Endl;        File << "Lasolmi" << Endl;    }    else cout << "can not open" <<endl;    File.close ();    return 0;}

Example: reading a text file
#include <iostream> #include <fstream>using namespace std;int main (int argc, char* argv[]) {    fstream file ("Test.txt", ios::in);    if (!file.fail ()) {        while (!file.eof ()) {            char buf[128];            File.getline (buf,128);            if (FILE.TELLG () > 0) {                cout <<buf;                cout    <<endl;    }}} else cout << "can not open" <<endl;    File.close ();    return 0;}

Example: Implementing File Replication.
Ifstream infile;ofstream Outfile;infile.open (infilename); if (!infile) {cout<< "fail open infile" <<ENDL;} Outfile.open (Outfilename); if (!outfile) {cout<< "fail open outfile" <<ENDL;} while (Infile.get (c)) outfile << c;infile.close (); Outfile.close ();

iOS provides a member function to detect or set the state of a stream.
int rdstate ();
int eof ();
int fail ();
int bad ();
int good ();
int clear (int flag=0);
In order to improve the reliability of the program, the operation of the I/O stream should be detected as normal. For example, open the text with fstream default mode


If the file does not exist, the FAIL function detects the error and then obtains the file status through the Rdstate method.
FStream file ("Test.txt");
if (File.fail ()) {
cout << file.rdstate () << Endl;
}
The append of the file.
Ofstream ofile ("Test.txt", Ios::app);
if (!ofile.fail ()) {ofile << append content;}
else cout << "can not open";
Append can be implemented using other methods, such as opening a file and then moving the file pointer to the end through the Seekp method, and then


Data, the entire process is the same as using the parameter values. Use the SEEKP method to implement the appended code as follows:
FStream iofile ("Test.dat", ios::in|ios::out|ios::binary); if (iofile) {    IOFILE.SEEKP (0,ios::end);//To write to move    Iofile << Endl;    Iofile << "I am a new addition";    IOFILE.SEEKG (0); In order to write the move    char data[100];    for (int i=0;! Iofile.eof () && i<sizeof (data); i++) Iofile.get (Data[i]);    cout << data;}

Judgment at the end of the file:
If the file pointer points to the end of the file, the Get method gets no data and returns-1, which can be used as a marker to end the judgment.
The same functionality can also be achieved using the EOF method.
Stream sp = Ifile.tellg (); SP is ifile pointer current position
Reads and writes files at the specified location. function to set the position of the file pointer:
SEEKG: Displacement byte number, relative position used to move the pointer in the input file.
SEEKP: Displacement byte number, relative position used to move the pointer in the output file.
TELLG: Used to find the position of the file pointer in the input file.
TELLP: Used to find the location of the file pointer in the output file.
Ios::beg: File header.
Ios::end: The tail of the file.
Ioe::cur: The current position of the file pointer.
Example: The output file specifies the location of the content.
#include <iostream> #include <fstream>using namespace std;int main (int argc,char* argv[]) {    ifstream ifile;    Char cfileselect[20];    cout << "input filename:";    Cin >> Cfileselect;    Ifile.open (cfileselect);    if (!ifile) {        cout << cfileselect << "Can not open" << Endl;        return 0;    }    IFILE.SEEKG (0,ios::end);    int maxpos = IFILE.TELLG ();    int pos;    cout << "Position:";    CIN >> POS;    if (pos > Maxpos)        cout << "is over file length" << Endl;    else {        char ch;        IFILE.SEEKG (POS);        Ifile.get (CH);        cout << ch <<endl;    }    Ifile.close ();    return 0;}

File and stream correlation and separation: A Stream object can represent different files at different times. When constructing a stream object, you do not have to


Binds the stream and file. Use the open member function of the stream object to dynamically bind to the file, if you want to associate other files


Use the close member function to close the current file connection to the stream, and then create a connection to the other file through the open member function.
Delete files, for example:
#include <iostream> #include <fstream>using namespace std;int main (int argc,char* argv[]) {    char file[50 ];    cout << "Input file name:" << "\ n";    cin >> file;    if (!remove (file))        cout << "The file:" << file << "deleted" << Endl;    else        cout << "The file:" << file << "Delete failed" <<endl;    return 0;}


C + + Learning Note 4--file operations

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.