利用C++写入和读取文件

在网上看了很多,发现写入文件内容的比较多

一、利用C++来写入文件

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    freopen("123.txt", "r", stdin);//打开文件
    freopen("123.txt", "w", stdout);//如果没有文件,则会自动进行添加
    //开始进行写入文件
    printf("hello world1");
    //写入完毕
    fclose(stdout);
    while (1);
    return 0;
}

二、读写操作

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
   //创建一个文本并向里面输入内容
    ofstream OutputFile("test.txt");//创建一个txt文本
    OutputFile << "hello meimei";//输入文本内容
    OutputFile.close();//关闭文件
    
    //读取文本的内容
     ifstream readstreamFile("test.txt");//打开test.txt的文本
     char a[1024];
     readstreamFile >> a;//这种方式的输出会导致只要遇到空格就会直接退出
    // readstreamFile.getline(a, 100, 0);//这种方式的输出是可以直接将里面的内容进行输出
     cout << a << endl;
     readstreamFile.close();
     while (1);
     return 0;
}


三、发现一篇大神的博客参考博客:https://blog.csdn.net/kingstar158/article/details/6859379

以下内容是参考大神博客进行改编

可以进行操作写入文本,并正确的读取出来

#include <iostream>
#include <fstream>
using namespace std;

int main() 
{
    //创建一个文本并向里面输入内容
    ofstream OutputFile("test.txt");//创建一个txt文本
    OutputFile << "hello meimei\n";//输入文本内容
    OutputFile << "hello shuige";
    OutputFile.close();//关闭文件


    //开始读取数据,这个情况的读取文件是全部进行读取
    char buffer[256];
    ifstream in("test.txt");
    if (!in.is_open())
    {
        cout << "Error opening file"; exit(1);
    }
    while (!in.eof()) 
    {
        in.getline(buffer, 100);//每行进行读取
        cout << buffer << endl;
    }
    while (1);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值