c++中的文件读写函数

这篇博客详细介绍了C++中进行文件读写操作的相关函数,包括使用头文件、命名空间等基础知识,并提供了CPP参考手册的链接,帮助读者深入理解并实践C++的文件I/O操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


头文件,命名空间

#include <fstream>
using name space std;


 

//函数
//构造函数,构造函数传入文件名称会尝试打开文件。
explicit basic_ifstream( const char* filename,
                std::ios_base::openmode mode = ios_base::in );	(2) 	
				
explicit basic_ifstream( const std::string& filename,
                std::ios_base::openmode mode = ios_base::in );	(4) 	(since C++11)
				
explicit basic_ifstream( const std::filesystem::path& filename,
                std::ios_base::openmode mode = ios_base::in );	(5) 	(since C++17)
				
basic_ifstream( basic_ifstream&& other ); 						(6) 	(since C++11)
	
/*
explicit 不接受隐式转换	https://baike.baidu.com/item/explicit/4941869?fr=aladdin
filename: 类型char*或string& ,要打开的文件名称,字符串内子目录符合是 "\\"
mode: 类型ios_base::openmode,打开方式
	ios::in 打开一个供读取的文件(ifstream流的默认值)
	ios::out 打开一个供写入的文件(ofstream流的默认值)
	ios::app 在写之前找到文件尾
	ios::ate 打开文件后立即将文件定位在文件尾
	ios::trunc 废弃当前文件内容
	ios::nocreate(已不再支持) 如果要打开的文件并不存在,那么以此参数调用open()函数将无法进行
	ios::noreplace (已不再支持) 如果要打开的文件已存在,试图用open()函数打开时将返回一个错误。
	ios::binary 以二进制的形式打开一个文件,默认为文本文件
官方手册没有第三个参数,实际有第三个参数
第三个参数:读写权限。类型int.默认是0x40,允许其他进程对自己打开的文件进行读写。
	#define _SH_DENYRW      0x10    /* deny read/write mode */拒绝对文件进行读写
	#define _SH_DENYWR      0x20    /* deny write mode */拒绝写入文件
	#define _SH_DENYRD      0x30    /* deny read mode */拒绝文件的读取权限
	#define _SH_DENYNO      0x40    /* deny none mode */读取和写入许可
	#define _SH_SECURE      0x80    /* secure mode */共享读取,独占写入

*/


/*返回打开状态 */
bool is_open();												(until C++11)
bool is_open() const;										(since C++11)

//文件打开和状态判断示例
#include <string>
#include <fstream>
#include <iostream>
//this file is called main.cpp
 
bool file_exists(const std::string& str)
{
   std::ifstream fs(str);
   return fs.is_open();
}
 
int main()
{
  std::boolalpha(std::cout);
  std::cout << file_exists("main.cpp")  << '\n'
            << file_exists("strange_file") << '\n';
}

/* 读取一行文本
basic_istream& getline( char_type* s, std::streamsize count );
	(1) 	
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );
	(2) 

*/
//读取行文本示例
#include <iostream>
#include <sstream>
#include <vector>
#include <array>
 
int main()
{
    std::istringstream input("abc|def|gh");
    std::vector<std::array<char, 4>> v;
 
    // note: the following loop terminates when std::ios_base::operator bool()
    // on the stream returned from getline() returns false
    for (std::array<char, 4> a; input.getline(&a[0], 4, '|'); ) {
        v.push_back(a);
    }
 
    for (auto& a : v) {
        std::cout << &a[0] << '\n';
    }
}

/* 读取指定数量的字符
basic_istream& read( char_type* s, std::streamsize count );
		
*/

//读取字符示例
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>
 
int main()
{
    // read() is often used for binary I/O
    std::string bin = {'\x12', '\x12', '\x12', '\x12'};
    std::istringstream raw(bin);
    std::uint32_t n;
    if(raw.read(reinterpret_cast<char*>(&n), sizeof n))
        std::cout << std::hex << std::showbase << n << '\n';
 
    // prepare file for next snippet
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";
 
    // read entire file into string
    if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
        auto size = is.tellg();
        std::string str(size, '\0'); // construct string to stream size
        is.seekg(0);
        if(is.read(&str[0], size))
            std::cout << str << '\n';
    }
}

参考手册

CPP参考手册中文
https://zh.cppreference.com/w/%E9%A6%96%E9%A1%B5

CPP参考手册
https://en.cppreference.com/w/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值