C ++ file read/write

Source: Internet
Author: User

I. ASCII output
To use the following method, you must include the header file <fstream. h> (Note: In Standard C ++, <fstream> has been used to replace <fstream. h>, all c ++ standard header files have no suffixes .). This is <iostream. h>. in fact, <iostream. h> already <fstream. h> yes, so you don't have to include all these two files. If you want to explicitly include them, you can. From the design of the file operation class, I will explain how to perform ascii I/O operations. If you guess it is "fstream," Congratulations! However, the methods described in this article use "ifstream "? And "ofstream" for input and output.
If you have used the standard console stream "Cin "? And "cout," the current thing is very simple for you. Let's start with the output section. First, declare a class object.
Ofstream fout; this is fine, but if you want to open a file, you must call ofstream: open () like this ().

Fout. Open ("output.txt"); you can also use the file name as a construction parameter to open a file.

Ofstream fout ("output.txt"); this is our method, because it looks easier to create and open a file. by the way, if the file you want to open does not exist, it will create one for you, so you don't have to worry about file creation. output to the file now. It looks like a "cout" operation. For those who do not understand the console output "cout", here is an example.

Int num = 150;
Char name [] = "John Doe ";
Fout <"here is a number:" <num <"/N ";
Fout <"Now here is a string:" <name <"/N"; to save the file, you must close the file or write back the File Buffer. after the file is closed, it cannot be operated again. Therefore, it is called only when you no longer operate the file. It will automatically save the file. The write-back buffer saves the file while keeping the file open, so you can use it whenever necessary. The write-back looks like another output, and the call method is disabled. Like this:

Fout <flush; fout. Close (); now you open the file in a text editor and the content looks like this:

Here is a number: 150 now here is a string: John Doe is simple! Now, it takes a bit of skill to continue entering files. First, make sure that you understand stream operations and are familiar with "<" and ">", because you will need to use them later. Continue...

Ii. ASCII Input
The input stream is similar to the "Cin" stream. It is similar to the output stream just discussed, but you need to consider several things. Before starting complex content, let's take a look at the text:

12 gamedev 15.45 L this is really awesome! To open this file, you must create an in-stream object ,? Like this.

Ifstream fin ("input.txt"); read the first four rows. Do you still remember how to use the "<" operator to insert variables and symbols into the stream? Okay ,? In "<" (insert )? After the operator, it is the ">" (extract) operator. The method is the same. Check this code snippet.

Int number;
Float real;
Char letter, word [8];
Fin> Number; Fin> word; Fin> real; Fin> letter; you can also write the code for reading these four lines of files into a simpler line.

Fin> number> word> real> letter; how does it work? After each blank space in the file, the ">" operator stops reading the content until another> operator is encountered. because each row we read is split by line breaks (blank characters), the ">" operator only reads the content of this row into the variable. This is why the code works normally. However, do not forget the last line of the file.

This is really awesome! If you want to read the entire row into a char array, you cannot use "> "? Operator, because the space (white space) between each word will stop reading the file. For verification:

Char sentence [101]; Fin> sentence; we want to include the entire sentence, "This is really awesome! "But because it is blank, it only contains" this ". Obviously, there must be a method to read the entire row. It is Getline (). This is what we need to do.

Fin. getline (sentence, 100); this is a function parameter. the first parameter is obviously used to accept the char array. the second parameter is the maximum number of elements allowed by the array before a line break occurs. now we get the expected result: "This is really awesome! ".
You should already know how to read and write ASCII files. But we can't stop, because the binary file is still waiting for us.

Iii. Binary Input and Output
Binary files are a little more complex, but they are still very simple. First, you must note that we do not use the insert and extract operators (<and> operators). You can do this, but it does not read or write data in binary format. You must use the read () and write () Methods to read and write binary files. Create a binary file and check the next line.

Ofstream fout ("file. dat", IOS: Binary); this will open the file in binary mode, instead of the default ASCII mode. Start with writing the file. The write () function has two parameters. The first is a pointer to the char type of the object, and the second is the size of the object (Note: number of bytes ). For illustration, let's look at the example.

Int number = 30; fout. write (char *) (& number), sizeof (number); write the first parameter as "(char *) (& number )". this is to convert an integer variable into a char * pointer. If you do not understand, you can read c ++ books immediately, if necessary. The second parameter writes "sizeof (number)". sizeof () returns the number of bytes of the object size. That's it!
The best way to write a binary file is to write a structure into the file in one row. If your structure has 12 different members. Use ASCII? File, you have to write all members each time. But the binary file is ready for you. Look at this.

Struct object {int number; char letter;} OBJ;
OBJ. Number = 15;
OBJ. letter = 'M ';
Fout. Write (char *) (& OBJ), sizeof (OBJ); this writes the entire structure! Next, the input. input is also very simple, because read ()? The parameters of the function are the same as those of the write () method.

Ifstream fin ("file. dat ", IOS: Binary); Fin. read (char *) (& OBJ), sizeof (OBJ); I will not explain the usage much because it is exactly the same as write. Binary files are simpler than ASCII files, but they cannot be edited using a text editor. Next, I will explain some other methods of the ifstream and ofstream objects as the end.

4. More Methods
I have explained the ASCII and binary files. Here are some underlying methods that are not mentioned.

Check files
You have learned the open () and close () methods, but there are other methods you may use.
Method good () returns a Boolean value indicating whether the file is opened correctly.
Similarly, bad () returns a Boolean value indicating whether the file is opened incorrectly. If an error occurs, do not proceed.
The last check method is fail (), which is similar to bad () but not so serious.

Read files
The get () method returns one character each time.
The ignore (INT, char) method skips a certain number of characters, but you must pass it two parameters. The first is the number of characters to be skipped. The second character is a character, which will be stopped when it is encountered. Example,

Fin. Ignore (100, '/N'); skips 100 characters or less than 100, including'/N '.
Method PEEK () returns the next character in the file, but does not actually read it. So if you use PEEK () to view the next character and read it after PEEK (), you will get the same character and move the file counter.
The putback (char) method is used to input one character at a time to the stream. I have never seen it, but this function does exist.

Write files
There is only one method you may be concerned about .? Put (char) writes a character to the output stream each time.

Open a file
When we use this syntax to open a binary file:

Ofstream fout ("file. dat ", IOS: Binary);" iOS: Binary "is an extra sign of the open option you provide. by default, files are opened in ASCII format. If files do not exist, they are created and overwritten if they exist. here, some additional flags are used to change the options.

IOS: add the app to the end of the file
IOS: ate puts the file mark at the end rather than the start point.
IOS: trunc. trunc truncates and overwrites files by default.
IOS: The nocreate file does not exist or is not created.
If the IOS: noreplace file exists, it fails.

File status
The only state function I have used is EOF (), which returns whether the flag has reached the end of the file. I mainly use it in a loop. For example, this code is used to calculate the number of times the lower case 'E' appears in the file.

Ifstream fin ("file.txt ");
Char ch; int counter;
While (! Fin. EOF ()){
Ch = fin. Get ();
If (CH = 'E') Counter ++;
}
Fin. Close (); I have never used other methods that are not mentioned here. There are many other methods, but they are rarely used. Refer to the help documentation of C ++ books or file streams to learn more about other methods.

Conclusion
You should have mastered how to use ASCII files and binary files. There are many ways to help you implement input and output, although few use them. I know many people are not familiar with file I/O operations. I hope this article will help you. Everyone should know that there are still many obvious methods for. file I/O ,? For example, the file <stdio. h> is contained. I prefer stream because it is simpler. Good luck to everyone who has read this article. Maybe I will write something for you later.

 

 

Both read and write operations must contain the <fstream> header file.

Read: reads data from external files to programs for processing.
For a program, data is read from the outside, so the input stream is defined, that is, the input stream object is defined: ifsteam infile, infile is the input stream object.
This object stores the data stream to be read from the file. Assume that the file named myfile.txt contains two rows of numerical data. The specific method is as follows:
Int A, B;
Ifstream infile;
Infile. Open ("myfile.txt"); // note the file path.
Infile> A> B; // two rows of data can be read continuously into the variable.
Infile. Close ()

If it is a large multi-row text file, you can read it like this:
Char Buf [1024]; // temporarily Save the Read File Content
String message;
Ifstream infile;
Infile. Open ("myfile. js ");
If (infile. is_open () // if the file is successfully opened, it indicates that something has been written.
{
While (infile. Good ()&&! Infile. EOF ())
{
Memset (BUF, 0, 10, 24 );
Infile. Getline (BUF, 1204 );
Message = Buf;
... // Some operations may be performed on the message.
Cout <message <Endl;
}
Infile. Close ();
}

Write: Write the processed data in the program to the file.
For a program, the data is written out, that is, the data leaves the program. Therefore, the output stream object ofstream OUTFILE is defined, and the OUTFILE is the output stream object, which is used to store the data to be written to the file. Specific Practices:
Ofstream OUTFILE;
OUTFILE. Open ("myfile. Bat"); // myfile. bat is the data storage file name.
If (OUTFILE. is_open ())
{
OUTFILE <message <Endl; // message is the data processed in the program.
OUTFILE. Close ();
}
Else
{
Cout <"file cannot be opened! "<Endl;
}

Example of C ++ reading/writing operations on files

/*/Read a line of characters from the keyboard, put the letters in the disk file fa2.dat in sequence, and then read it from the disk file into the program,
Change the lowercase letters to uppercase letters and store them in the disk fa3.dat */
# I nclude <fstream>
# I nclude <iostream>
# I nclude <cmath>
Using namespace STD;
//////////// Function for reading characters from the keyboard
Void read_save (){
Char C [80];
Ofstream OUTFILE ("f1.dat"); // open the file with an outputer
If (! OUTFILE ){
Cerr <"Open error! "<Endl; // note that cerr is used
Exit (1 );
}
Cin. Getline (C, 80); // read a line of characters from the keyboard
For (INT I = 0; C [I]! = 0; I ++) // processes the characters one by one until '/0' is encountered.
If (C [I]> = 65 & C [I] <= 90 | C [I]> = 97 & C [I] <= 122) {// ensure that the entered character is a character
OUTFILE. Put (C [I]); // saves letters to Disk Files
Cout <C [I] <"";
}
Cout <Endl;
OUTFILE. Close ();
}
Void creat_data (){
Char ch;
Ifstream infile ("f1.dat", IOS: In); // open the file as input
If (! Infile ){
Cerr <"Open error! "<Endl;
Exit (1 );
}
Ofstream OUTFILE ("f3.dat"); // defines the output stream f3.dat File
If (! OUTFILE ){
Cerr <"Open error! "<Endl;
Exit (1 );
}
While (infile. Get (CH) {// when the character is successfully read
If (CH <= 122 & ch> = 97)
Ch = ch-32;
OUTFILE. Put (CH );
Cout <ch;
}
Cout <Endl;
Infile. Close ();
OUTFILE. Close ();
}
Int main (){
Read_save ();
Creat_data ();
System ("pause ");
Return 0;
}

This article from the csdn blog, the original address: http://blog.csdn.net/shtianhai/archive/2008/05/02/2363841.aspx

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.