C + + file read and write summary

Source: Internet
Author: User

How to read and write files in C + +? Author: infobillows Published: 2007-04-03 21:33 Hits: 4,651, ASCII output in order to use the following method, you must include the header file <fstream.h> (Translator Note: in standard C + +, you have already used <fstr Eam> replaces < 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 included in <fstream.h>, so you don't have to include all of these two files, if you want to explicitly include them, then whatever you like. We start with the design of the file operation class and I'll explain how to do the ASCII I/O operation. If you guessed "fstream," Congratulations on your right answer! However, this article describes the method, we use "Ifstream" and "ofstream" for input and output. If you've used the standard console flow "cin"? and "cout," then things are easy for you now. Let's start with the output section and declare a class object first. Ofstream Fout; That's all right, 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 that we use because it is easier to create and open a file. By the way, if you want to open a file that does not exist, it will create one for you, so don't worry about file creation issues. Output to a file now, looks like the "cout" operation. Here's an example of a person who doesn't understand the console output "cout". int num = 150;char name[] = "John Doe"; Fout << "Here is a number:" << num << "/n"; Fout << "Now he Re is a string: "<< name <<"/n "; Now save the file, you must close the file, or write back the file buffer. The file cannot be manipulated after it is closed, so it is only called when you no longer manipulate the file, it automatically saves the file. The write-back buffer will keep the file openSave the file, so use it whenever necessary. Writeback looks like another output, and then the call method closes. Like this: Fout << flush; Fout.close (); Now you open the file with a text editor, and the content looks like this: Here is a number:150 today here's a String:john Doe is simple! It's a bit tricky to continue with file input now, so make sure you understand the flow, and you're familiar with << and >>, because you're going to need them next. Go on... Two, the ASCII input input and the "CIN" stream is very similar. It looks 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! In order to open this file, you must create a In-stream object, like this. Ifstream fin ("input.txt"); Now read in the first four lines. Do you remember how to use the "<<" operator to insert variables and symbols into the stream? OK, after the "<<" (insert) operator, it is the ">>" (extract) operator. The use method is the same. 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 the code for the four-line read file as a simpler line. Fin >> number >> word >> real >> letter; How does it work? After each blank in the file, the >> operator stops reading the content until another >> operator is encountered. Because each line we read is separated by a newline character (which is a white space), the ">>" operator only reads the contents of this line into the variable. That's why this code works as well. However, don't forget the last line of the file. This is really awesome! If you want to read the entire line into a char array, we can't use the ">>" operator because the space between each word (the white space character) aborts the file's reading. In order to verify: Char sentence[101];Fin >> sentence; We want to include the whole sentence, "This is really awesome!" but because of the blank, now it 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 parameter. The first parameter is obviously a char array to accept. The second parameter is the maximum number of elements that the array allows 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 binary input and output binaries can be a bit more complicated, but it's still simple. First you should note that we no longer use the insert and extract operators (translator:<< and >> operators). You can do this, but it does not read and write in binary mode. You must use the read () and write () methods to read and write binary files. Create a binary file and look at the next line. Ofstream fout ("file.dat", ios::binary); This opens the file in binary mode instead of the default ASCII mode. Start by writing to the file first. The function write () has two parameters. The first is a pointer to the char type of the object, and the second is the size of the object (translator: number of bytes). To illustrate, look at the example. int number = 30; Fout.write ((char *) (&number), sizeof (number)); The first parameter is written "(char *) (&number)". This is converting an integer variable to a char * pointer. If you don't understand, you can read the C + + books right away, if necessary. The second parameter writes "sizeof (number)". sizeof () returns the number of bytes of the object size. That's it! The best place for binary files is to write a structure to a file on a single line. If you say, your structure has 12 different members. With an ASCII file, you have to write all the members one at a time. But the binaries are 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 will write the entire structure! Next is the input. The input is also simple because the parameters of the read () function are exactly the same as the write (), and the same method is used. Ifstream fin ("file.dat", ios::binary); Fin.read ((char *) (&obj), sizeof (obj)); I don't explain usage much, because it is exactly the same as write (). Binary files are simpler than ASCII files, but one drawback is that they cannot be edited with a text editor. Next, I explain some of the other methods of Ifstream and Ofstream objects as the end. Four, more methods I have explained the ASCII file and the binary file, here are some of the underlying methods that are not mentioned. Check the 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 was opened correctly. Similarly, bad () returns a Boolean value indicating whether the file was opened incorrectly. If there is an error, do not proceed further. The last method to check is fail (), which is somewhat similar to bad (), but less severe. The Read file 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 one is the number of characters that need to be skipped. The second one is a character that stops when it is encountered. Example, Fin.ignore (+, '/n '); Skips 100 characters, or less than 100, skips all previous characters, including '/n '. The method Peek () returns the next character in the file, but does not actually read it. So if you use PEEK () to see the next character, read it after Peek () with Get (), you get the same character, and then you move the file counter. Method Putback (char) enters the character, one at a time, into the stream. I have not seen its use, but this function does exist. There is only one way you might be interested in writing a file. That is put (char), which writes one character to the output stream at a time. Open the file when we open the binary file with this syntax: Ofstream fout ("file.dat", ios::binary); "Ios::binary" is an additional flag that you provide with the option to open. By default, the file is opened in ASCII mode, does not exist, is created, 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 instead of the start. Ios::tRunc default. Truncate and overwrite files. 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 ever used is EOF (), which returns whether the flag has reached the end of the file. I use it mainly in the loop. For example, this code breaks down the number of occurrences of lowercase ' e ' 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 ways, but they are seldom used. Refer to the C + + book or file flow Help documentation to learn about other methods. Conclusion you should have mastered how to use ASCII files and binaries. There are many ways to help you achieve input and output, although few people use them. I know many 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 include file <stdio.h>. I prefer to use flow because they are simpler. Good luck to all who read this article, and maybe I'll write something for you later. Include <fstream> header file read: Read data from an external file into a program for the program to read data from the outside, so define the input stream, which defines the input stream object: The Ifsteam infile,infile is the input stream object. This object holds the data stream that is about to be read from the file.      Suppose there is a file named MyFile.txt, there are two lines of digital data, the specific method: int a,b;ifstream infile;infile.open ("MyFile.txt");                   Note the path to the file infile>>a>>b;                Two rows of data can be read continuously into the variable infile.close () if it is a large multi-line stored text file can read this: char buf[1024]; Temporarily save the read-out file contents of string Message;ifstream infile;infile.open ("Myfile.js"); if (Infile.is_open ())//file opened successfully, indicating that something was written {W Hile (Infile.good () &&!infile.eof ()) {memset (buf,0,1024);   Infile.getline (buf,1204);   message = BUF; ...//There may be some manipulation of the message here cout<<message<<endl; } infile.close ();} Write: Write the data processed in the program to the file in the program is to write the data out, that is, the data out of the program, so the definition of the output stream object Ofstream Outfile,outfile is the output stream object, which is used to store the data will be written to the file.  Specific practices: Ofstream outfile;outfile.open ("Myfile.bat");    Myfile.bat is the file name that holds the data if (Outfile.is_open ()) {outfile<<message<<endl; The message is the data processed in the program Outfile.close ();} else{cout<< "Can't open file!" <<endl;} C + + read and write operation of the file example/*/from the keyboard reading a line of characters, the letters placed in the disk file Fa2.dat, and then read it from the disk file into the program, the lowercase letters to uppercase, and then into the disk Fa3.dat */#i nclude< Fstream>#i nclude<iostream>#i nclude<cmath>using namespace std;      function to read characters from the keyboard void Read_save () {char c[80]; Ofstream outfile ("F1.dat");//Export the file if (!outfile) {cerr<< "open error!")                   <<endl;//Note is the use of Cerr exit (1); } cin.getline (c,80);//read a line of characters from the keyboard for (int i=0;c[i]!=0;i++)//one-to-one processing of characters until the encounter of '/0 ' so far if (c[i]>=65&&c[i]<=90| | c[i]>=97&&c[i]<=122) {//guaranteed input characters are character outfile.put (C[i]);//Save alphabetic characters to disk file Cout&l                   t;<c[i]<< "";                   } cout<<endl;                   Outfile.close ();      } void Creat_data () {char ch; Ifstream infile ("F1.dat", ios::in);//Open file as input if (!infile) {cerr<< "Open error!"                  <<endl;                  Exit (1); } ofstream outfile ("F3.dat");//define output stream F3.dat file if (!outfile) {cerr<< "Open error!"                 <<endl;                 Exit (1);     } while (Infile.get (CH)) {//When reading the word Fu Chenggong 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; }

  

C + + file read and write summary

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.