C++入门(4):文件读写
对文件进行读写要包含下面的头文件:
#include <fstream>
ofstream: 输出文件流,文件名可以是绝对路径名或相对路径名
ifstream: 输入文件流
std::ofstream fileOutput0(".\\fileTest\\file0.txt"); //将fileOutput0变量与一个特定的文件关联在一起
if(fileOutput0.is_open()) //使用is_open()函数来确认这个文件已被打开,或者使用fileOutput0.good()函数确认
{
std::cout << "The file has been opened successfully!" << std::endl;
fileOutput0 << "Please write something...\n" ; //向文件写数据
fileOutput0.close(); //及时关闭文件
}
else
{
std::cout << "The file cannot be opened successfully!" << std::endl;
return 1; //如果不能打开,返回一个状态
}
如果使用上面的方法定义了一个文件变量fileOutput0,则即使关闭了这个文件,在程序以后的变量定义中也都不能再使用fileOutput0来定义另外一个文件变量了。
为了解决这个问题,可以使用open()函数:它用同一个文件变量打开多个文件,即先打开一个文件并把它关联到fileOutput变量,用完之后关闭它,然后再打开一个文件并把它关联到fileOutput变量。
std::ofstream fileOutput1; //可以先创建一个ofstream类型的变量,再调用open()函数打开一个文件
fileOutput1.open(".\\fileTest\\file1.txt") ;
fileOutput1 << "The first time to use the parameter! \n";
fileOutput1.close();
fileOutput1.open(".\\fileTest\\file2.txt") ; //关闭之后可以使用这个文件变量打开另一个文件
fileOutput1 << "The second time to use the parameter! \n";
fileOutput1.close();
给现有文件增加数据:
std::string user;
std::ofstream fileOutput2(".\\fileTest\\file0.txt", std::ios::app); //给现有文件增加数据
if(fileOutput2.is_open()) //打开文件时进行检测是很有用的,可以避免很多不必要的错误
{
std::cout << "What do you want to add to the file!" << std::endl;
std::getline(std::cin, user); //先读入一行数据到变量user
fileOutput2 << user << std::endl; //再把user写入文件
fileOutput2.close();
}
else
{
std::cout << "The file cannot be opened successfully!" << std::endl;
return 1;
}
从文件读取数据:
也可以利用字符串拼接操作符,把一个完整的文件读入一个大字符串。
std::string line,entireTxt;
std::cout << entireTxt; //entireTxt初始化是个空串
std::ifstream fileInput3(".\\fileTest\\file0.txt"); //定义一个ifstream类型的变量表示读取,从文件读取数据时,文件必须已经存在
if(fileInput3.is_open()) //文件成功打开之后,可以进行读取数据的操作
{
while(std::getline(fileInput3,line)) //getline()用于文件,表示从特定文件读取一行数据,把数据赋给变量line
{
entireTxt += line; //字符串拼接
}
fileInput3.close(); //一定要及时关闭文件
std::cout << entireTxt;
}
else
{
std::cout << "The file cannot be opened successfully!" << std::endl;
return 1;
}