From: http://www.vckbase.com/document/viewdoc? Id = 1439
Use C ++ for simple file I/O operations
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
It 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>.
<Fstream. h> all the C ++ standard header files have no suffixes .). This is an extension set of <iostream. h>. It provides buffered file input and output.
Operation. In fact, <iostream. h> has been included by <fstream. h>, so you do not 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! But this article
In this article, we use "ifstream" and "ofstream" for input and output respectively.
If you have used standard console streams "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
Create one, so you don't have to worry about file creation. Now output to the file, it looks like the "cout" operation. For those who do not know 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, you cannot operate it any more.
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. Write-back looks like
For another output, call the method to disable it. 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 the file, so first confirm that you understand the stream operation and are familiar with "<" and ">", because you have received
They will be used 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? Well, after the "<" (insert) operator, it is "> "(
Operator. The usage is the same. Check the 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 file, the ">" operator stops reading content until another> operator is encountered.
All rows are separated by linefeeds (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 the ">" operator because spaces (blank characters) between each word will stop reading files.
. 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
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 desired 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 ).
You can do this, but it does not read or write in binary format. You must use the read () and write () Methods to read and write binary files. Create a binary file,
Check the next row.
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 one is pointing
The Char pointer of the object, and the second is the object size (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 the C ++ book 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. You have
Each time a row is written to all members. But the binary file is ready for you. Check 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 the parameters of the read () function are the same as those of the write () function.
.
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 that you may concern about. It is put (char), which writes one character each time to the output stream.
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 provided by you. It is opened in ASCII format by default. If the file does not exist, it is created and overwritten.
Is used to change the options.
IOS: app added to the end of the file IOs: ate put the file mark at the end rather than the start. IOS: trunc. trunc truncates and overwrites files by default. IOS: nocreate file does not exist
Do not create. 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 breaks down statistics in lower case
The number of times '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 for more information.
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 many obvious methods for. file I/O, such as package
Including files <stdio. h>. I prefer stream because they are simpler. Good luck to everyone who has read this article. Maybe I will write something for you later.