Input and output [C ++] refresher (ix) file

This is a C ++ class to brush up on the ninth chapter study notes, and other articles with topics can venue: https://www.jianshu.com/nb/39156122

Input and output document is also based on the flow (stream) of, and cout, cinsimilar operations.

Write to the file

Basic conditions

  • It must include the header file fstream
  • Header file fstreamdefines processing for outputting the ofstreamclass
  • Need to declare one or more ofstreamvariables (objects), and named
  • You must specify the namespace std
  • We need to ofstreamassociate objects with the file up. One way is to use the open()method
  • After finished with the file, the method should be used close()to turn it off
  • It may be used in conjunction with ofstreamobjects and operators <<outputs various types of data

Examples of a written document

#include<fstream>
using namespace std;
 
int main()
{
    string myString = "hello world!";

    ofstream ourFile;
    outFile.open("myFile.txt");
    outFile << myString;
    outFile.close();

    return 0;
}

Read the file

Basic conditions

  • It must include the header file fstream
  • Header file fstreamdefines processing for the input ifstreamclass
  • Need to declare one or more ifstreamvariables (objects), and named
  • We need to ifstreamassociate objects with the file up. One way is to use the open()method
  • After reading the file, the method should be used close()to turn it off
  • It may be used in conjunction with ifstreamobjects and operators >>to read various types of data
  • You can use ifstreamthe object and get()to read a character method, ifstreamthe object and getline()to read a line of characters
  • Can be used in combination ifstreamand cof(), fai()like the success of the method to determine whether the input
  • ifstreamWhen the object itself is used as the test condition, if the last read operation is successful, it will be converted to a Boolean value true, or is converted tofalse

Examples of a file read

#include<fstream>
#include<iostream>
using namespace std;
 
int main()
{
    string fileName = "myFile.txt";

    ifstream inFile;
    inFile.open(fileName);
    if (!inFile.is_open())
    	cout << "Can't open the file: " << fileName;

    string readText;
    inFile >> readText;

    if (inFile.eof())
    	cout << "End of file reached.\n";
    else if (inFile.fail())
    	cout << "Input terminated by data mismatch.\n";
    else
    	cout << "Input terminated for other reasons.\n";

    inFile.close();

    return 0;
}

Please indicate the source, permanently updated links in this article: https://blogs.littlegenius.xin/2019/08/28/【C- refresher nine] input and output file /

Published 44 original articles · won praise 46 · views 9154

Guess you like

Origin blog.csdn.net/qq_38962621/article/details/100128577