2020-12-11 C++文件操作

1. 判断文件是否存在

#include<io.h>

if(access(path, 0) == 0)
{
    cout<<"文件存在"<<endl;
}
else
{
     cout<<"文件不存在"<<endl;  
}

int _access(const char *pathname, int mode);//位于<io.h>中

返回0是正确

2. 新建一个文件

#include <fstream>



fstream ff(path, ios::trunc | ios::out);
ff.close();

3. 读文件

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

void main()
{

    string str;
	fstream f1("./a.txt", ios::in);
	
	f1>>str;        //读到第一个空格、换行为止
    cout<<str<<endl;
    
    f1.seekg(0,ios::beg);  //文件指针指回到开头
    
    
    getline(f1, str);    //读到换行为止, 也就是读一整行
    cout<<str<<endl;
       
	f1.close();
}

a. text 

this is a test

输出:

this
this is a test

4. 写文件

#include<fstream>
#include<iostream>
#include<string>

using namespace std;

void main()
{

    string str;
	//fstream f1("./a.txt", ios::out);             //原文件会先被清空再写入
	//fstream f1("./a.txt", ios::out|ios::trunc);  //原文件会先被清空再写入
	
    //fstream f1("./a.txt", ios::app);             //在原文件后追加
	fstream f1("./a.txt", ios::out|ios::app);      //在原文件后追加
	
    
    f1<<"this is a simple test"<<endl;
       
	f1.close();
}

C++的文件操作还是很简单的,但是用ios::out和ios::trunc方式打开文件时,要小心数据丢失。

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值