Summary: How to write the output to the file in C + + __c++

Source: Internet
Author: User
The article is I searched the forehead some experience summary on the net.
C + + writes output to file

File I/O is much simpler than baking a cake in C + +. In this article, I'll explain in detail every detail of the input and output of ASCII and binary files, and it's worth noting that all of this is done in C + +.

First, ASCII output

In order to use the following method, you must include the header file <fstream.h> (Translator Note: in standard C + +, you have used <fstream> instead of < Fstream.h> all C + + standard header files are no suffix.) )。 This is an extended set of <iostream.h> that provides buffered file input and output operations. In fact, <iostream.h> has been <fstream.h> included, so you don't have to include all these two files, if you want to include them explicitly, that's fine with you. Let's start with the design of the file manipulation class, and I'll explain how I am doing ASCII I/O. If you're guessing "fstream," congratulations. But the method described in this article, we use "Ifstream" and "ofstream" for input and output respectively.

If you've used the standard console stream "cin" and "cout," then things are simple for you now. Let's start with the output section and declare a class object first. Ofstream Fout;

That's OK, but if you want to open a file, you have to call Ofstream::open () like this.

Fout.open ("output.txt");

You can also open a file with the filename as a construction parameter.

Ofstream fout ("output.txt");

This is the method we use because it looks simpler to create and open a file. By the way, if you're going to open a file that doesn't exist, it will create one for you, so don't worry about the file creation problem. Now the output to the file, looks like the "cout" operation is very similar. For people who don't know the "cout" of the console output, here's an example.

int num = 150;
Char name[] = "John Doe";
Fout << "Here is a number:" << num << "\ n";
Fout << "Now this is a string:" << name << "\ n";

Now save the file, you must close the file, or write back the file buffer. After the file is closed, it cannot be manipulated, so it is only invoked when you no longer operate the file, it automatically saves the file. The write-back buffer saves the file while the file is open, so use it whenever necessary. Writeback looks like another output, and then calls the method close. Like this:

Fout << Flush; Fout.close ();

Now you open the file with a text editor, and it looks like this:

Here are a number:150 now this is a String:john Doe

It's simple! Now continue with the file input, you need a bit of skill, so make sure you understand the flow operation, the "<<" and ">>" more familiar, because you need to use them next. Go on...

Two, ASCII input

The input is similar to the "CIN" stream. Like the output stream just discussed, but you have to consider a few things. Before we start the complex content, look at a text:

GameDev 15.45 L This is really awesome!

To open this file, you have to create a In-stream object, like this.

Ifstream fin ("input.txt");

Now read the first four lines. You remember how to use the "<<" operator to insert variables and symbols into the stream. After the "<<" (insert)? operator, it is the ">>" (extract) operator. The same method is used. Look at this code fragment.

int number;
float Real;
Char letter, Word[8];
Fin >> number; Fin >> Word; Fin >> Real; Fin >> Letter;

You can also write code that reads the files in these four lines as a simpler line.

Fin >> number >> word >> real >> letter;

How does it work? After each white space in the file, the ">>" operator stops reading until another >> operator is encountered. Because each line we read is separated by a newline (a blank character), the ">>" operator reads only the contents of the line into the variable. That's why this code works as well. But don't forget the last line of the file.

This is really awesome!

If you want to read the whole line into a char array, we can't use the ">>" operator, because the space between each word (a white space character) aborts the file's reading. To verify:

Char sentence[101]; Fin >> sentence;

We want to include the entire sentence, "This is really awesome!" but because of the whitespace, it now contains only "this". Obviously, there must be a way to read the whole line, which is getline (). That's what we're going to do.

Fin.getline (sentence, 100);

This is the function argument. The first parameter is obviously a char array to accept. The second parameter is the maximum number of elements that the array is allowed to accept before a newline character is encountered. Now we have the desired result: "This is really awesome!".

You should already know how to read and write ASCII files. But we can't stop, because the binaries are still waiting for us.

Three or two feed input and output

Binary files can be a bit more complicated, but they're simple. First you should note that we no longer use the insert and extract operators (translator:<< and >> operators). You can do this, but it doesn't read and write in binary form. You must read and write binary files using the read () and write () methods. Create a binary file and look at the next line.

Ofstream fout ("file.dat", ios::binary);

This will open the file in binary mode, not the default ASCII mode. Start by writing to the file first. The function write () has two parameters. The first is a pointer to the object's char type, and the second is the size of the object (the number of bytes). To illustrate, see examples.

int number = 30; Fout.write ((char *) (&number), sizeof (number));

The first parameter is written as "(char *) (&number)." This is the conversion of an integer variable to a char * pointer. If you do not understand, you can immediately read the C + + books, if necessary. The second parameter is written "sizeof (number)". sizeof () returns the number of bytes in the object size. That's it!

The best place for a binary file is to write a structure to a file on one line. If you say, you have 12 different members of the structure. With ASCII file, you have to write all the members one at a time. But binaries are done 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 will write the entire structure! Next is the input. The input is also simple, because the parameters of the read () function and write () are exactly the same, and the same method is used.

Ifstream fin ("file.dat", ios::binary); Fin.read ((char *) (&obj), sizeof (obj));

I don't explain the usage much, because it's exactly the same as write (). Binary files are simpler than ASCII files, but there is a disadvantage that you cannot edit them with a text editor. Next, I explain some other methods of Ifstream and Ofstream objects as an end.

Iv. More methods

I've explained ASCII files and binaries, and here are some low-level methods that are not mentioned.

Check file

You've learned the open () and close () methods, but there are other ways you might use them.

Method Good () returns a Boolean value that indicates whether the file is open correctly.

Similarly, bad () returns a Boolean value indicating whether the file was open incorrectly. If there is an error, do not proceed with further action.

The final check was fail (), a bit similar to bad (), but not so serious.

Read files

Method Get () returns one character at a time.

Method Ignore (Int,char) skips a certain number of characters, but you must pass it two arguments. The first is the number of characters that need to be skipped. The second one is a character that stops when it encounters it. Example

Fin.ignore (+, ' \ n ');

Skips over 100 characters, or less than 100, skips all previous characters, including ' \ n '.

Method Peek () returns the next character in the file, but does not actually read it. So if you look at the next character with Peek () and read it after Peek (), you get the same character and move the file counter.

Method Putback (char) to enter characters, one at a time, into the stream. I have not seen it used, but this function does exist.

Write a file

There's only one way you might be concerned. That is put (char), which writes one character to the output stream at a time.

Open File

When we open the binary file with this syntax:

Ofstream fout ("file.dat", ios::binary);

"Ios::binary" is an additional sign for opening options that you provide. By default, the file is opened in ASCII mode, is created without existence, and is overwritten. Here are some additional flags to change the options.

Ios::app add to end of file
Ios::ate the file flag at the end rather than the start.
Ios::trunc default. Truncate and overwrite the file.
The Ios::nocreate file does not exist or is not created.
The Ios::noreplace file exists and fails.

File status

The only state function I've used is EOF (), which returns whether the flag is already at the end of the file. I mainly use in the loop. For example, this code breaks statistics the number of lowercase ' e ' occurrences in a 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 ways, but they are rarely used. Consult a C + + book or file flow Help document to learn about other methods.

Conclusion

You should have mastered how to use ASCII and binary files. There are many ways to help you achieve input and output, although few people use them. I know a lot of people are unfamiliar with file I/O operations and I hope this article will help you. Everyone should know. There are many obvious ways to file I/O, such as including file <stdio.h>. I prefer to use the flow because they are simpler. Good luck to all those who read this article, perhaps I will write something for you later.






In the view of C + + programming thought, each practice basically is uses ofstream,ifstream,fstream, before roughly knew its usage and the meaning, after saw several Daniel's Bowen, carries on the collation and the summary:


This is mainly about FStream:


[Java] view plain copy print?

#include <fstream>

Ofstream//File write operation memory write storage device

Ifstream//file read operation, storage device read in memory

FStream//read/write operation, can read and write to open files




1. Open the file

In the FStream class, the member function open () implements the operation of opening a file, associating the data flow with the file, and reading and writing to the file through the Ofstream,ifstream,fstream object

Function: Open ()


[CPP] view plain copy print?

<span style= "Font-family:times New roman;font-size:16px;" >

Public member function

void Open (const char * filename,

Ios_base::openmode mode = Ios_base::in | Ios_base::out);

void Open (const wchar_t *_filename,

Ios_base::openmode mode= Ios_base::in | Ios_base::out,

int prot = Ios_base::_openprot);

Parameters: filename operation filename


Mode how to open a file

Prot Open File Properties//Basic rarely used, in view of the data, found that there are two ways

The way you open a file is defined in the iOS class (so the base class of streaming I/O), there are several ways:


Ios::in Open file for input (read)
Ios::out Open file for output (write)
Ios::ate Initial position: End of File
Ios::app All outputs are appended to the end of the file
Ios::trunc If the file already exists, delete the file first
Ios::binary Binary mode
These methods can be used in combination with the "or" Operation ("|"). ) in the way: for example


[CPP] view plain copy print?

Ofstream out;

Out.open ("Hello.txt", ios::in|ios::out|ios::binary)                // Do the appropriate

for your own needs.

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.