如何使用C和C++读写文件

读文件方法:
在这里插入图片描述

代码:

#include <stdio.h>
#include <fstream>
#include <iostream>

void CreateFile(const char * file_name);
void ReadFileUseC(const char * file_name);
void ReadFileUseCPP(const char * file_name);

int main(){
        const char file_name[] = "test.txt";
        CreateFile(file_name);
        ReadFileUseC(file_name);
        ReadFileUseCPP(file_name);
        std::cout << "game over!" <<  std::endl;
        return 0;
}

void CreateFile(const char * file_name){
        printf("create file %s\n", file_name);
        std::ofstream fout;
        fout.open(file_name, std::ios::out);
        fout << "hello,world" << std::endl;
        fout << "i love china" << std::endl;
        fout.close();
}

void ReadFileUseC(const char * file_name){
        FILE * fp = fopen(file_name, "r");
        char buff[256] = {0};
        int index = 0;
        while(1){
                char c = fgetc(fp);
                if(c == EOF){
                        break;
                }

                buff[index] = c;
                index++;
        }
        fclose(fp);
        printf("read file use c:\n%s", buff);
}

void ReadFileUseCPP(const char * file_name){
        std::ifstream fin;
        fin.open("test.txt", std::ios::in);

        if(!fin.is_open()){
                std::cout << "file open failed!" << std::endl;
                return;
        }

        char c = '\0';
        std::string file_content;
        while(fin.get(c)){
                file_content += c;
                c = '\0';
        }
        fin.clear();
        fin.close();
        std::cout << "read file use c++:\n" << file_content.c_str();
}

输出:

[root@localhost test]# ls
main.cpp
[root@localhost test]# g++ -o demo main.cpp 
[root@localhost test]# ls
demo  main.cpp
[root@localhost test]# ./demo 
create file test.txt
read file use c:
hello,world
i love china
read file use c++:
hello,world
i love china
game over!
[root@localhost test]# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值