C + + file operations: Open files and write files

Source: Internet
Author: User

If the program's running results are displayed only on the screen, you must rerun the program again when you want to view the results again, and the result cannot be persisted.
If you want the results of your program to be permanently preserved for viewing or fetching at any time, you need to save it in a file.

File classification

external files and internal files

    1. External files: Refers to disk files, which are also commonly called files.
    2. Internal file: Refers to the file running in the program, the more formal title is "file Stream object".
    3. The internal files are manipulated in the program, and the external files are finally saved.

Text files and binaries

    1. Text file: Consists of a sequence of characters, with characters (character) for accessing the smallest unit of information, also known as an "ASCII code file."
    2. Binary file: consists of binary numbers.
Use procedure

This section only discusses the use and operation of text files and their simple applications.
The process of using a text file is fixed, and the general steps are as follows:

(1) Open a file, make the disk file and file stream object to establish contact;

( 2) writes data to a file as text, just as cout is used to send data to the monitor. The data can be read from this file later, just as CIN is used for keyboard input.

(3) When the file is no longer in use, to close the file, the file is completely written back to the disk from the buffer. This allows the data to be persisted permanently.

Operation Steps

1. Describes a file stream object (internal file).

Example: Ifstream ifile;//Description input File stream object IFile

Ofstream ofile;//Description output file stream object Ofile
Description

    • The file stream type Ifstream supports the operation of extracting data from the input file.
    • The file stream type Ofstream completes the various operations that the data writes to the output file.
    • IFile is an input file stream object for reading; ofile is an output file stream object for writing.

2. Open the file and establish a connection between the file stream object and the disk file.

For example: Ifile.open ("D:\\my_in_file.txt");

Ofile.open ("D:\\my_out_file.txt");

Description

    • A string in double quotation marks (such as "D:\\my_in_file.txt") is the disk file path name.
    • Opening the specified disk file by entering a file stream object (such as ifile) or an output file stream object (such as ofile) will establish a connection between the file stream object and the disk file.
    • The input/output file stream objects are called "internal files", which are "virtual files" that are associated with the corresponding disk file.

3. Read and write to the file.

    • File reads and writes are performed in the file buffer.
    • The most common file reads and writes are sequential, starting with the file header.
    • Sequential reads and writes can be performed using the extraction operator (>>) of C + + and the Insert operator (<<), or a function such as the Get () of the read character and the Getline () of the read string.

4. Close the file.
After the file operation is finished, you should explicitly close the file, as opposed to opening the file, for example:

Ifile.close ();

Ofile.close ();
When the file is closed, the system writes the data in the file buffer associated with the file to the disk file, guaranteeing the integrity of the file, and disconnecting the disk file name from the file stream object, which prevents the disk file from being modified by mistake.

Application examples

"Example 2.25" The results of the hundred chicken problem calculation into a file.

1#include <fstream>2#include <iomanip>3  using namespacestd;4  intMain () {5      inti,j,k;6Ofstream ofile;//Defining output Files7Ofile.open ("D:\\myfile.txt");//Open as output file8ofile<<"Rooster hen Chick"<<endl;//Title Write File9      for(i=0; i<= -; i++)Ten           for(j=0; j<= -; j + +){ Onek= --i-J; A              if((5*i+3*j+k/3== -) && (k%3==0))//Note (k%3==0) is very important -OFILE&LT;&LT;SETW (6) &LT;&LT;I&LT;&LT;SETW (Ten) &LT;&LT;J&LT;&LT;SETW (Ten) <<k<<endl;//data written to file -         } theOfile.close ();//Close File -     return 0; -}

"Example 2.26" reads the file that holds the calculation result of hundred chicken problem

1#include <fstream>2#include <iostream>3#include <iomanip>4  using namespacestd;5  intMain () {6      Chara[ -];7Ifstream ifile;//Defining input Files8Ifile.open ("D:\\myfile.txt");//Open as input file9     intI=0, j,k;Ten       while(IFile.Get(A[i])) {//read the title, please compare Cin.get (), not available >>, it cannot read white characters One         if(a[i]=='\ n') Break; Ai++; -      } -a[i]=' /'; thecout<<a<<Endl; -       while(1){ -ifile>>i>>j>>k;//read data into the file -         if(ifile.eof ()! =0) Break;//ifile.eof () is true when the end of the file is read +COUT&LT;&LT;SETW (6) &LT;&LT;I&LT;&LT;SETW (Ten) &LT;&LT;J&LT;&LT;SETW (Ten) <<k<<endl;//Screen Display -      } +Ifile.close ();//Close File A     return 0; at}

Important Notes

    • The 1th and 2 steps of the procedure can be combined into 1 steps, which means that the file stream object is opened with the corresponding disk file. For example:

Ifstream ifile ("D:\\my_in_file.txt");//Description input File stream object IFile and open file

Ofstream ofile ("D:\\my_out_file.txt");//Description output file stream object ofile and open file

    • When a file is opened, such as a disk file does not exist, the file is automatically created, but the specified directory must exist or the file fails to be established.
    • The computer also manages external devices as files. For example: The keyboard and monitor are standard input and output files with the filenames of CIN and cout.
    • Disk file operations are very similar to keyboard and monitor operations. In an example, the output file stream object (such as ofile) instead of cout, the input file stream object (such as ifile) instead of CIN, the whereabouts and source of the data are changed from the monitor and keyboard to the disk file.
    • To manipulate the file, you must add a sentence before the program: #include <fstream>

C + + file operations: Open files and write files

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.