Simple file input and output

Simple file input and output

  • Include the header file fstream
  • Ofstream class defines the output for processing a
  • Ofstream need to declare one or more variables, and ofstream objects associated with the file.
  • Wherein an association method using open () method, after using the file using the close () Close method.
  • Ofstream objects and can use the << operator outputs various types of data.
  • Note, ofstream must declare themselves.
ofstream outFile;
outFile.open("fish.txt");
outFile << "hhhh"<<endl; //向文件中输入一行文本
  • ofstream object can use any method to cout.
  • open () function
    • If you run before the file does not exist, create the file. If there are changes to its length is 0 (empty).
    • open () may fail to open.
  • Fstream header file that contains the file read
  • Ifstream defines a class for processing input
  • Need to declare ifstream object.
  • Ifstream objects need to be associated with the file, use the open () method.
  • Use close () method to close.
  • Ifstream >> used to read various types of data.
  • get ifstream object () method to read a character. Use getline () reads a line of characters.
  • It may be combined and used ifstream eof (), fail () determines whether or not successful or the like.
  • When ifstream object itself as a test condition, if the last read operation was successful, it is converted to type bool
ifstream inFile;
inFile.open("bowling.txt");
double wt;
inFile >> wt;
char line[81];
inFile.getline(line, 81);
  • Use is_open () to determine whether the file is opened. exit () function is defined in the header file cstdlib. If the compiler does not support is_open (), you can use the older good () instead.
inFile.open("bowling.txt");
if (!inFile.is_open())
{
    exit(EXIT_FAILURE);
}
  • An error occurred during reading
    • If you encounter EOF, eof () function returns true
    • Encountered type mismatch or EOF, fail () returns true
    • Returns true if the disk is damaged or corrupted files, bad ()
    • If you want to simply determine whether the reading is successful, the use of good (). Returns true on success
    inFile >> value;
    while(inFile.good())
    {
      //...
      inFile >> value;
    }
    //另一种简洁写法
    while(inFile >> value)
    {
      //...
    }

Guess you like

Origin www.cnblogs.com/yangzixiong/p/11973894.html