c++笔记08---I/O 流,格式化 I/O,非格式化 I/O,随机 I/O,二进制 I/O

本文介绍了C++中的I/O流,包括格式化I/O(<< / >>)、非格式化I/O(put/get)、随机I/O、二进制I/O,并通过示例展示了如何进行文件的读写操作。此外,还讲解了如何进行二进制文件的加解密以及格式控制,如设置精度、进制转换等。

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

1.    输入输出 I/O 流        
    C: fopen/fclose/fread/fwrite/fprintf/fscanf/fseek/ftell/fput/fget...
    C++: 对基本的 I/O 操作做了类的封装,其功能没有任何差别,用法也相似;
    
2.    格式化 I/O 流:<< / >>
        #include <iostream>
        #include <fstream>                        // 打开文件
        using namespace std;
        int main() {
            // 写文件:
            ofstream ofs("hello.txt");            // 创建文件,类似于 fopen 用 w 模式,只读且清空
            // ofs 在 ofstream 的构造函数里面被构造,打开成功返回 ture,失败返回 false,是 bool 型;
            if(! ofs) {
                perror("error");                    // perror 打印出错信息;
                return -1;
            }
            ofs << "hello word!"  << endl;        // hello word! 被输入文件 hello.txt 里;
            ofs.close();

            ofs.open("hello.txt", ios::app);    // 打开文件,追加内容,类似于 fopen 的 a 模式
            if(! ofs) {
                perror("error");
                return -1;
            }
            ofs << "another\n";
            ofs.close();
            // 读文件:
            ifstream ifs("hello.txt");
            if(! ifs) {
                perror("error");
                return -1;
            }
            steing s1, s2;
            ifs >> s1 >> s2;                        // 读入上面输入的两个字符串;以空白字符作为分隔(空格、换行、制表);
            return 0;
        }
        
        ios::app    以追加的方式打开文件;
        ios::ate    文件打开后定位到文件尾;
        ios::binary    以二进制方式打开文件;缺省是文本方式;
        ios::in        以输入方式打开;
        ios::out        以输出方式打开;
        ios::nocreate    不建立文件,所以文件不存在时,打开失败;
        ios::noreplace    不覆盖文件,所以打开文件时,如果文件存在则失败;
        ios::trunc        如果文件存在,把文件长度设为 0;
        ios::beg            移动到文件头;
        ios::cure            移动到文件当前位置;
        ios::end            移动到文件尾;
        可以用 或 把以上文件属性连接起来:
        
    
3.    非格式化 I/O 流:put/get
        #include <iostream>
        #include <fstream>
        using namespace std;
        int mian() {
            // 输入
            ofstream ofs("putget.txt");
            if(! ofs) {
                perror("error");
                return -1;
            }
            for(char c = ' '; c <= '~'; ++c)    // 把 ASIIC 表里的字符从第一个到最后一个写入;
            // 前++返回引用,后++返回副本,所以建议用前++,效率高;
                if(! ofs.put(c)) {
                    preeor("error");
                    return -1;
   &n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值