C++ || 文件的读取与保存

1 文件读取

使用C++读取保存文件,实现是比较简单的。在这里记录下,两种方式都能够正确的读取文本。
但如果文本中的每个数据中间隔的不是空格,是【, /】之类的。第二种方式,有sscanf的使用,就会更加方便和灵活。


1.1 使用std::ifstream

假设 test.txt 数据为:

v 1 2
v 2 3
v 4 5
v 6 7

#
v 9 0

用std::ifstream 进行文件读取,注意while的条件。(用法不正确时,会出现文本最后一行重复读取两边)

#include <vector> 
#include <string>
#include <sstream>  // 字符串流,在这里是 std::stringstream 所需的头文件
#include <fstream>   // 对文件输入输出
#include <iostream>  //对屏幕上输入输出
using namespace std;

bool readTXT(string name)
{
   std::ifstream fout1(name.c_str());
   if (!fout1.is_open())
   {
       printf("无法正确读取文件");
       return false;
   }
   while (!fout1.eof())
   {
       string line;
       getline(fout1, line);
       std::stringstream data(line);
       
       string s, a1, b1;
       data >> s >> a1 >> b1;
       printf("%s %s %s\n", s, a1, b1);
   }
   return true;
}

void main()
{
    readTXT("test.txt");
}

在这里插入图片描述


1.2 使用 File进行

#include <vector> 
#include <string>
#include <sstream>  // 字符串流,在这里是 std::stringstream 所需的头文件
#include <fstream>   // 对文件输入输出
#include <iostream>  //对屏幕上输入输出
using namespace std;

bool begins_with(const char *s1, const char *s2)
{
   return !_strnicmp(s1, s2, strlen(s2));
}
bool readTXT1(string name)
{
   FILE *f = fopen(name.c_str(), "rb");
   while (1)
   {
       if (feof(f))
           break;
       char buf[1024];
       fgets(buf, 1024, f);
       if (begins_with(buf, "v "))
       {
           string s;
           int v1, v2;
           if (sscanf(buf, "%s %d %d", &s, &v1, &v2) != 3) {
               return false;
           }
       printf("%s %d %d\n", s, v1, v2);
       }
   }
   return true;
}

void main()
{
    readTXT("test.txt");
}

在这里插入图片描述

2 保存文件

使用下面方式,即可快速保存

#include <vector> 
#include <string>
#include <sstream>  // 字符串流,在这里是 std::stringstream 所需的头文件
#include <fstream>   // 对文件输入输出
#include <iostream>  //对屏幕上输入输出
using namespace std;

bool saveTEXT1(string name)
{
   std::ofstream fout1(name.c_str());
   if (!fout1.is_open())
   {
       printf( "没有正确创建文件");
       return false;
   }
   for (int i = 0; i < 2; i++)
   {
       fout1 << "be well" << " " << i << endl;
   }
   fout1.close();
   return true;
}

void main()
{
    saveTEXT1("save.txt");
}
  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值