使用std::fstream处理文件
C++提供了std::fstream,旨在以独立于平台的方式访问文件。std::fstream从std::ofstream那里继承了写入文件的功能,并从std::ifstream那里继承了读取文件的功能,换句话说std::fstream提供了读写文件的功能。
要使用std::fstream,需要包含头文件#include<fstream>
使用open()和close()打开和关闭文件
要使用fstream、ofstream、ifstream类,需要使用open()打开文件:
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ofstream myFile;
myFile.open("D:/hello.txt", ios_base::out);// out用来写入
if (myFile.is_open())
{
cout << "File open successful" << endl;
myFile << "My first text file!" << endl;//输入字符串
myFile << "Hello file!";//输入字符串
cout << "Finished writing to file, will close now" << endl;
myFile.close();
}
return 0;
}
使用open()和运算符>>读取文本文件
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream myFile;
myFile.open("D:/hello.txt", ios_base::in);
if (myFile.is_open())
{
cout << "File open successful. It contains: " << endl;
string fileContents;
while (myFile.good())
{
getline (myFile, fileContents);// 用getline()来从myfile读取一行到stringfileContents
cout << fileContents << endl;
}
cout << "Finished reading file, will close now" << endl;
myFile.close();
}
else
cout << "open() failed: check if file is in right folder" << endl;
return 0;
}
读写二进制文件
#include<fstream>
#include<iomanip>
#include<cstring>
#include<iostream>
using namespace std;
struct Human
{
Human() {};
Human(const char* inName, int inAge, const char* inDOB) : age(inAge)
{
strcpy(name, inName);
strcpy(DOB, inDOB);
}
char name[30];
int age;
char DOB[20];
};
int main()
{
Human Input("Siddhartha Rao", 101, "May 1916");
ofstream fsOut ("MyBinary.bin", ios_base::out | ios_base::binary);
if (fsOut.is_open())
{
cout << "Writing one object of Human to a binary file" << endl;
fsOut.write(reinterpret_cast<const char*>(&Input), sizeof(Input));
fsOut.close();
}
ifstream fsIn ("D:hello.bin", ios_base::in | ios_base::binary);
if(fsIn.is_open())
{
Human somePerson;
fsIn.read((char*)&somePerson, sizeof(somePerson));
cout << "Reading information from binary file: " << endl;
cout << "Name = " << somePerson.name << endl;
cout << "Age = " << somePerson.age << endl;
cout << "Date of Birth = " << somePerson.DOB << endl;
}
return 0;
}
使用std::stringstream对字符串进行转换
#include<fstream>
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
cout << "Enter an integer: ";
int input = 0;
cin >> input;
stringstream converterStream;
converterStream << input;
string inputAsStr;
converterStream >> inputAsStr;
cout << "Integer Input = " << input << endl;
cout << "String gained from integer = " << inputAsStr << endl;
stringstream anotherStream;
anotherStream << inputAsStr;
int Copy = 0;
anotherStream >> Copy;
cout << "Integer gained from string, Copy = " << Copy << endl;
return 0;
}
运行结果如上图所示。