C++入门(4):文件读写

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

C++入门(3):输入、输出

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值