Use C ++ for simple file I/O operations

Source: Internet
Author: User

Source: simple file I/O using C ++

Sequence Theory
I have published an article on file input and output, and now I think it is necessary to write more. File I/O is much easier than baking cake in C ++. In this article, I will explain in detail every detail of the input and output of ASCII and binary files. It is worth noting that all these are completed in C ++.

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 the construction parameter to open a file.

ofstream fout("output.txt");

This is the method we use, because it is 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. The content looks like this:

Here is a number: 150 Now here is a string: John Doe 

Easy! 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"); 

Now 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)); 

The first parameter is written 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)); 

In this way, the entire structure is written! 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’); 

The system skips 100 characters or less than 100 characters, 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 additional identifier 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: app Add to end of File
IOS: ATE Put the file mark at the end rather than the start point.
IOS: trunc By default, files are truncated and overwritten.
IOS: nocreate The file does not exist or is created.
IOS: noreplace Failed if the file exists.

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.

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.