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);
}