"Studious C + + 2nd Edition" chapter 8th file-Electronic storage

Source: Internet
Author: User
Tags printable characters

Main memory (RAM, random access memory) its data is lost when the computer shuts down.

For the function calls and operations supported by CIN and cout, the file stream provided by C + + is also supported. The former requires # include <IOSTREAM> the latter requires # include <fstream>. Stream is the destination when writing data, and is the source when reading the data.

Open Badgirl.txt File:

Ofstream fout ("Badgirl.txt"); Open the file exclusively, the default file in the current directory (the directory running the program), you can also give the full path (plus the drive letter can also, this is the absolute path, such as "C:\\badgirl.txt" is the absolute path of the C:\badgirl.txt file). and Ifstream and FStream.

Fout << "You sexy girl!" << Endl;

Fout << "Need bad boy!"

Fout.close ();

The Fout object provides a path to a disk file. In object-oriented terms, the Fout encapsulates the file and makes it capable of receiving output data. In addition, although the program exits successfully, C + + automatically closes the file that is still open, but it is best to close the file when it is not used, so that the program discards ownership of the file so that other processes can access it. It: Does a process open a file and other processes can read and write the file? Is there an error attempting to open the file?

Char filename[max_path+1];

Predefined constants MAX_PATH: The maximum length of a file name (including its path) that the system can support.

If the file open operation is unsuccessful, the fout will be null and can be used for judgment. An illegal path or opening a read-only file as if it were written would return null.

if (!fout) {/*...*/}

The Ifstream fin;//file is opened in text and input mode.

Fin.getline (Input_line, col_width+1);//read out a line

if (fin.eof ()) {/*...*/}; At the end of the file, Fin.eof () is true.

The library function atoi can convert a string to an integer, which can be used to handle user input.

These are text streams, and the operation is similar to console IO. Each byte written to a file is an ASCII encoding of printable characters.

Binary files: This type of file is read and written using the actual value of the data, without the need for ASCII conversion (it: the number 0 is written to the number 0, not the ASCII value of 0).

# # # #文本模式里, newline characters are converted to \n\r (carriage return plus line wins) or \ n (Unix) or \ r (MAC) when writing. In binary mode, this type of conversion is not required. # # # #注: Enter the original intent is the cursor back to the beginning of the current line, newline intent is to move the cursor to the next line. So do not taunt wins, meaning is complete, though one more character. However, the problem is the cross-system file format problem, which produces the Dos2unix command.

When you create a file stream object, you can set it to either text mode (default) or binary mode. The former should use <<, >>, and Getline, which should only use the read and write member functions (which are direct read and write operations).

Example: (a record refers to a data format that repeats itself in a file.) Because the data is arranged in a regular order, it is easy to get the data through the record number, and it is natural to save them with structs or classes (subsequent discussions). )

#include <iostream>

#include <fstream>

using namespace Std;

int get_int (int default_value);

int main () {

Char filename[max_path+1];

int n = 0;

Char name[20];

int age = 0;

int recsize = sizeof (name) + sizeof (int);//Calculate the length of the record

Open File

cout << "Enter file name:";

Cin.getline (Filename,max_path);

FStream fbinout (filename, ios::binary | ios::out); Ios::out is to write to the file, note that the existing file content is overwritten, and the new file is opened

if (!fbinout) {

cout << "Could not open" << filename <<endl;

System ("PAUSE");

return-1;

}

  

Get the data to log

cout << "Enter record number:";

n = get_int (0); Get record number

cout << "Enter Name:"

Cin.getline (name, sizeof (name)); Get the name

cout << "Enter Age:";

Age = Get_int (0); Get age

  

Write Data

FBINOUT.SEEKP (n * recsize); Offset from the record number to the location where the record should be, otherwise it will overwrite record No. 0 (it: cursor or pointer default at the very beginning of record No. 0)

Fbinout.write (name, sizeof (name));

Fbinout.write ((char*) (&age), sizeof (int));

Fbinout.close ();

  

System ("PAUSE");

return 0;

}

#define COL_WIDTH 80//80 is a typical line width//it: precompilation comes into effect at the definition

int get_int (int default_value) {

Char s[col_width+1];

Cin.getline (S, col_width+1);

if (strlen (s) = = 0)

return default_value;

return atoi (s);

}

Reading data is similar, except that:

FStream fbinin (filename, ios::binary | ios::in); Ios::in mode file does not exist error

FBININ.SEEKP (n*recsize);

Fbinin.read (name, sizeof (name));

Fbinin.read ((char*) (&age), sizeof (int));

Fbinin.close ();

The following fbin will support both read and write support:

FStream fbin (filename, ios::binary | ios::out | ios::in);

Summary leackage Check:

#include <fstream> activates the file stream support feature provided by the C + + standard library (introducing the necessary function prototypes and declarations into the program)

It: The random access pattern can be implemented through file pointers (including overwriting any part of the file without affecting other data). If the file pointer is moved to a location that exceeds the current length of the file, the file is automatically expanded to meet the length requirement.

The SEEKP member function is used to move a file pointer whose entry is an offset (in bytes) from the beginning of the file header.

Read and write: The entry parameter is the same, both the data address (char* type) and the number of bytes that need to be copied. It: Write int to take its address to the char* type, but the number of bytes copied is still the number of bytes occupied by int (recommended for sizeof).

Fbin.write ((char*) (&x), sizeof (x));

"Studious C + + 2nd Edition" chapter 8th file-Electronic storage

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.