C ++ learning notes for file operations

Source: Internet
Author: User
Tags traits

=========================================== Preface ====================== ====================

When writing a program, we perform operations on the file. We can read data from the file and save the data to the file ......

In a word, operations on files are very important. Next we will introduce how operations on files in C ++.

========================================== Function display ================ ======================

  • File output operations

To output data from a program to a file, you need to perform the following five steps:

Include fstream header file: # Include <fstream>

Create an ofstream object: Ofstream ocout;

Associate objects with files: Ocout.open(‑test.txt ");

Use this object to output data to the file test: Ocout <"hello, C ++ !";

Close the connection to the file: Ocout. Close ();

P.s. Here we apply the object ocout of ofstream to directly output data to the file, rather than on the screen!

Complete program example:

?
1234567891011 #include <fstream>using
namespace std;int
main()
{    ofstream ocout;    ocout.open("test.txt");    ocout<<"Hello,C++!";    ocout.close();    return
0;}

After running the program, we will find a test.txt file in the program's directory. After opening the file, "Hello, C ++!" will be displayed !". As shown in

Note that we can also merge the rows 6th and 7th of the above program into one sentence:

?
ofstream ocout("test.txt");

This statement calls the constructor in the ofstream class to create the text file. In addition, we need to pay special attention to the fact that, after completing operations on the entire file, we must use the close () function to close the file. Otherwise, after the program ends, the operated file will not be saved !!!

  • Read data from a file

The method for reading data from a file is basically the same as that for outputting data to the collection. It also requires five steps:

IncludeFstreamHeader file: # Include <fstream>

Create an ifstream object: Ifstream icin;

Associate objects with files: Icin.open(‑test.txt ");

Use this object to read data from the file test to the array temp: Icin> temp;

Close the connection to the file: Icin. Close ();

P.s is the same as above. We can also combine steps 1 and 2 into one sentence:

?
ifstream icin("test.txt");

The function is to call the constructor in the ifstream class to read the local text file.

Complete program example:

?
12345678910111213 #include <fstream>#include <iostream>using
namespace std;int
main()
{    ifstream icin;    icin.open("test.txt");    char
temp[100];// Define a character array temp    icin>>temp;// Read the data in the file to the character array temp    cout<<temp<<endl;// Output the content stored in temp to the screen    return
0;}

Before shipment, you must create the test.txt file under the folder. The content of the file is "Hello, C ++ !". The output is as follows:

As you can see, the program displays the content in the test.txt text file in the command line.

  • How to read characters After Spaces  

When writing a file, spaces are inevitable. However, the insertion operator of C ++ has a problem. It will stop output as soon as it encounters null characters. The null character here is a space or '\ 0 '. In this way, if the file contains space characters, the characters after the space cannot be output to the screen. For example, the content in the created test.txt file is: Hello C ++! Replace the comma after hello with a space. Then run the program again and the output is as follows:

Is there any solution? Of course, yes. Use the Getline () function. Below is a piece of msdn introduction to the prototype and parameters of the Getline () function:

The first is the function prototype:

template<class CharType, class Traits, class Allocator>   basic_istream<CharType, Traits>& getline(      basic_istream<CharType, Traits>& _Istr,      basic_string<CharType, Traits, Allocator>& _Str);template<class CharType, class Traits, class Allocator>   basic_istream<CharType, Traits>& getline(      basic_istream<CharType, Traits>& _Istr,      basic_string<CharType, Traits, Allocator>& _Str,      const CharType _Delim); 

The parameters in the function have been expressed in the black box. The following describes the parameters:

_ Istr the input stream from which a string is to be extracted. specifies the buffer to be output. _ STR the string into which are read the characters from the input stream. read the character data in the stream _ delim the line delimiter. end symbol (the default end symbol is '\ n'. Here, the default end symbol is replaced with a custom end symbol. It means that the output stops when _ delim is encountered)

Now, with this function, we can change the 10th rows in the above program:

?
icin.getline(temp,100);

This means that all the content in the character array temp is read to the screen, as shown in

OK ~~ In this way, we are not afraid of spaces in the file.

In addition, if we want to write a paragraph in the command line, and this section contains spaces and carriage returns, we should use the third parameter of the Getline () function above, because there may be carriage return in a paragraph, we must use the third function of Getline () to replace the default ending symbol '\ N' with an empty character' \ 0 '. This is because the ASCII code of the null character is 0, and it is impossible to enter the null character in the file. Therefore, the Getline () function will read until the end of the file. How can I stop user input? The method is actually very simple. After we enter a paragraph, we will press Enter. Then we should send the EOF sign to the function, that is, the end mark (end
Of file ). The command line uses "Ctrl + z" to send the file Terminator, and then press the Enter key again to stop the input.
P.s. Space is not an empty character, and its ASCII code is 32.

Next, let's use a practical example to demonstrate: first read a paragraph and then output it to the file:

?
#include <iostream>#include <fstream>using
namespace std;int
main()
{    const
int num=255;    char
temp1[num]={0};// Initialize the array temp1    char
temp2[num]={0};// Initialize the array temp2    // ① Output data to the text.txt File    ofstream f_out("text.txt");    cout<<"Enter the text: \ n";    cin.getline(temp1,num,0);    f_out<<temp1;    f_out.close();    // ② Re-read the content in text.txt to the screen    ifstream f_in("text.txt");    f_in.getline(temp2,num,0);    cout<<temp2<<endl;    return
0;}

Analysis of the entire program:
① Output data to text.txt
First, we define the output stream object f_outof a file in row 11and create a text.txt text file with the object. Then, the Getline () function is used in the second row of the program to accept the text content and put it in the temp1 character array. Note: The third parameter of the Getline () function here is a null character, indicating that it can accept spaces and can stop reading users' keyboard input only when it reaches the end of the file. Well, if we press Ctrl + z after entering the file, then press enter again to stop the input. In the 14th line of the program, we use the ofstreamobject foutto output the content in the buffer area to the text file text.txt. Close the file.
② Re-read the content in text.txt to the screen.
In the same output example, we first define the input stream object f_infor a file in the 17th line of the program, and use the object to read the newly created text.txt text file. Then, call the getlin () function to output the content in the file to the character array temp2, and then use cout to output the content of the temp2 array to the screen. In this way, the input and output operations on the file are completed.

The running result is as follows:

OK !!! Program output successful !! However, this program has a small flaw. Check the output result above and we can see that in the command line, "Please press any key to continue ..." There is a carriage return on it! What's going on? We didn't output one more carriage return?

Actually, there are !!!! Note: Then I returned a car and then output Ctrl + Z, and sent a file end sign to the Getline () function. Then, in order to end the program, press enter again. In this case, the 2nd press enter is automatically discarded because it exceeds the file Terminator EOF. However, the first press enter is! The carriage return is not discarded, but written into the temp1 function. This is the problem. Therefore, after the output, we will see that "Please press any key to continue ..." There is a carriage return on it! The solution to this problem is actually very simple. We only need to change the last enter to an empty character '\ 0. Add the following two sentences after the 13 lines of the program:

?
12 int
n=
strlen(temp1);temp1[n-1]='\0';

The first sentence means to read the length of visible characters in the character array temp1 and save it to the integer Variable N. The second sentence means to find the subscript of the element that saves the Enter key, then, assign a value to the element of the base object to an empty character. The complete procedure is as follows:

?
1234567891011121314151617181920212223 #include <iostream>#include <fstream>using
namespace std;int
main()
{    const
int num=255;    char
temp1[num]={0};// Initialize the array temp1    char
temp2[num]={0};// Initialize the array temp2    // ① Output data to the text.txt File    ofstream f_out("text.txt");    cout<<"Enter the text: \ n";    cin.getline(temp1,num,0);    int
n=strlen(temp1);    temp1[n-1]='\0';    f_out<<temp1;    f_out.close();    // ② Re-read the content in text.txt to the screen    ifstream f_in("text.txt");    f_in.getline(temp2,num,0);    cout<<temp2<<endl;    return
0;}

Then there is the program output:

Okay, I finally got this program done. It's so troublesome !!! Call ~~

This blog post has recorded so much. Next time I will learn how to operate C ++ on files, ^_^

  

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.