补充一个简单的读文件数据和存数据到文件 【20200501】:
使用C语言fscanf和fgets函数读取txt文件数据【这两个函数在C++中照样可以使用】
具体见:【https://blog.csdn.net/sinat_32602421/article/details/105880331】,这里再将【https://blog.csdn.net/sinat_32602421/article/details/105880331】里面的读取方式用C++的函数来读取:
C++语言读取文件数据——getline函数和string类:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct stru
{
char c[10];
int a;
char arr[10];
};
//C++向文件存入数据
void writeFile()
{
ofstream fout;
fout.open("0501.txt", ios::out);
if (!fout.is_open())
{
cout << "文件打开失败" << endl;
return;
}
fout << "1234" << ' ' << "hello" << endl;
fout << "1234hello" << endl;
fout << 3.1415 << ' ' << "hello" << endl;
fout << 3.1415 << ' ' << "hello";
fout.close();
cout << "数据存储完成" << endl;
}
//使用C++读取文件
void ReadFile1()
{
ifstream fin;
fin.open("0501.txt", ios::in);
if (!fin.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//读取第一行:直接使用fin //ifstream fin;
string buf1;
getline(fin, buf1);
cout << "line 1:" << buf1 << endl;
//读取第2行:getline
string buf2;
getline(fin, buf2);
cout << "line 2:" << buf2 << endl;
//分解第2行
string buf2_1;
buf2_1.assign(buf2, 0, 4);//buf2_1 = buf2.substr(0, 4);
cout << "line 2_1:" << buf2_1 << endl;
string buf2_2;
buf2_2.assign(buf2, 4, 5);//buf2_2 = buf2.substr(4, 5);
cout << "line 2_2:" << buf2_2 << endl;
//读取第3行和第4行,这两行格式相同
struct stru stru1[2]; //定义结构体数组,装这两行数据
int line = 0;
while (!fin.eof())
{
string Tstr;
getline(fin, Tstr);
cout << "line" << line + 3 << ": " << Tstr << endl;
strcpy(stru1[line].arr, (Tstr.substr(0, 6)).c_str());
stru1[line].a = atof(stru1[line].arr); //将字符串"3.1415"转为浮点数3.1415
strcpy(stru1[line].c, (Tstr.substr(7, 5)).c_str());
cout << "line" << line + 3 << "_1: " << stru1[line].arr << endl;
cout << "line" << line + 3 << "_2: " << ' ' << stru1[line].c << endl;
line += 1;
}
fin.close();
cout << "数据读取完成\n" << endl;
}
int main()
{
writeFile();//使用C++写文件
ReadFile1();//使用C++读取文件
return 0;
}
说明:
向文件中存储数据:
1】
2】
3】
4】
从文件中读取数据:
5】
6】getline函数的使用参考【http://c.biancheng.net/view/1533.html】
7】
8】
9】
=================================================
二进制文件写数据: 说明: 二进制写数据,打开看是乱码。
—————————————————————————————————— 二进制文件读数据:
| |
读文本文件: (给出四种读取方法) 1】
2】 3】 4】
| |
20200422 | 写文件(文本):
|