Use C ++ for simple file I/O operations

Source: Internet
Author: User

FileI/OInC ++It is much easier than baking a cake. 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.

 
 
  1. ofstream fout; 

This is fine, but if you want to open a file, you must call ofstream: open () like this ().

 
 
  1. fout.open("output.txt"); 

You can also use the file name as the construction parameter to open a file.

 
 
  1. 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.

 
 
  1. int num = 150;  
  2. char name[] = "John Doe";  
  3. fout << "Here is a number: " << num << "\n";  
  4. 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:

 
 
  1. 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.

 
 
  1. 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.

 
 
  1. int number;   
  2. float real;   
  3. char letter, word[8];   
  4. 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.

 
 
  1. 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 between each word is blank) will stop reading the file. For verification:

 
 
  1. 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.

 
 
  1. 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.

 
 
  1. 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.

 
 
  1. int number = 30;   
  2. 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.

 
 
  1. struct OBJECT { int number; char letter; } obj;   
  2. obj.number = 15;  
  3. obj.letter = ‘M’;   
  4. 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.

 
 
  1. ifstream fin("file.dat", ios::binary);   
  2. 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,

 
 
  1. 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:

 
 
  1. 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: 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.

 
 
  1. ifstream fin("file.txt");   
  2. char ch; int counter;   
  3. while (!fin.eof()) {  
  4. ch = fin.get();   
  5. if (ch == ‘e’) counter++;   
  6. }  
  7. 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.