C++文件的数据写入和文件的数据读取的方法实现

目录
  • 一:没有数据,准备数据,写入文件
  • 二:读文件操作

一:没有数据,准备数据,写入文件

1.main.cpp

#include<iostream>
using namespace std;
#include<fstream>
#include<string>
#include<list>
#include"CData.h"
#include"CStaff.h"

int main()
{
	CData::userInit();//数据初始化
	return 0;
}

2.CStaff.h

#ifndef CSTAFF_H
#define CSTAFF_H
#define ADMIN 1
#define MANAGER 2
#define WAITER 3
#include<string>
#include<iostream>
using namespace std;

class Staff
{
public:
	Staff();
	Staff(int id,string name,string pwd,int prole);
	~Staff();
	int getId();
	string getName();
	string getPwd();
	int getRole();
private:
	int ID;
	string name;
	string pwd;
	int role;
};

#endif
 

3.CStaff.cpp

#include"CStaff.h"
#include<iostream>
using namespace std;

Staff::Staff()
{
}

Staff::Staff(int id,string name,string pwd,int prole)
{
	this->ID = id;
	this->name = name;
	this->pwd = pwd;
	this->role = prole;
}

int Staff::getId()
{
	return this->ID;
}

string Staff::getName()
{
	return this->name;
}

string Staff::getPwd()
{
	return this->pwd;
}

int Staff::getRole()
{
	return this->role;
}

Staff::~Staff()
{
}

4.CData.h

#ifndef CDATA_H
#define CDATA_H
#include<list>
#include"CStaff.h"

//专门用来做数据准备  文件存储在磁盘中 程序运行在内存中
//缓存区 链表 向量    适合什么样的容器
class CData
{
public:
	//静态:不通过对象 属于类 类名::静态成员/静态函数
	static list<Staff> staffList;
	static void userInit();      //用户数据初始化
};

#endif

5.CData.cpp

#include"CData.h"
#include<fstream>
#include<iostream>
using namespace std;

list<Staff> CData::staffList; //静态成员的初始化

//实现类的静态函数
void CData::userInit()
{
	/*
	1.从文件中读取数据 存入list
	2.如果没有数据 先预定义一些数据写入文件 存储list3个
	3.如果有数据 读取出来存入list
	*/
	fstream fs;//文件流对象  in从文件中读出 out写入文件 app追加
	fs.open("user.txt",fstream::in | fstream::out |fstream::app);
	//目标读文件 文件指示器需要定在开头
	//如果没有数据 定位到文件尾部 获取文件大小
	fs.seekg(0, ios::end);
	//计算文件中的字节数
	int count = fs.tellg();
	//创建一个迭代器
	list<Staff>::iterator it;
	if(count<=0)
	{
		cout<<"没有数据,准备数据,写入文件"<<endl;
		CData::staffList.push_back(Staff(1001,"admin","123",ADMIN));
		CData::staffList.push_back(Staff(1002,"lily","123",MANAGER));
		for(it = CData::staffList.begin();it!=CData::staffList.end();it++)
		{
			//fs写入 每个元素是对象.运算符获取
			//每个数据一行 用空格隔开
			fs<<(*it).getId()<<" "<<(*it).getName()<<" "<<(*it).getPwd()<<" "<<(*it).getRole()<<endl;
		}
	}
}

结果:

二:读文件操作

CData.cpp

#include"CData.h"
#include<fstream>
#include<iostream>
using namespace std;

list<Staff> CData::staffList; //静态成员的初始化

//实现类的静态函数
void CData::userInit()
{
	/*
	1.从文件中读取数据 存入list
	2.如果没有数据 先预定义一些数据写入文件 存储list3个
	3.如果有数据 读取出来存入list
	*/
	fstream fs;//文件流对象  in从文件中读出 out写入文件 app追加
	fs.open("user.txt",fstream::in | fstream::out |fstream::app);
	//目标读文件 文件指示器需要定在开头
	//如果没有数据 定位到文件尾部  获取文件大小
	fs.seekg(0, ios::end);
	//计算文件中的字节数
	int count = fs.tellg();
	//创建一个迭代器
	list<Staff>::iterator it;
	if(count<=0)
	{
		cout<<"没有数据,准备数据,写入文件"<<endl;
		CData::staffList.push_back(Staff(1001,"admin","123",ADMIN));
		CData::staffList.push_back(Staff(1002,"lily","123",MANAGER));
		for(it = CData::staffList.begin();it!=CData::staffList.end();it++)
		{
			fs<<(*it).getId()<<" "<<(*it).getName()<<" "<<(*it).getPwd()<<" "<<(*it).getRole()<<endl;
		}
	}
	else
	{
		//目标读文件 文件指示器定位到开头
		fs.seekg(0,ios::beg);
		char buf[256] = {0};
		int id = 0,role = 0;
		char pwd[10]={0};
		char name[10]={0};
		while(fs.peek()!=EOF)//EOF是读到末尾
		{
			//没有读到最后 每一行都读取
			fs.getline(buf,256);
			//sscanf读到数据 使用空格进行拆分
			sscanf(buf,"%d %s %s %d",&id,name,pwd,&role);
			//拆分出来的数据 放入链表中
			CData::staffList.push_back(Staff(id,name,pwd,role));
		}
		for(it = CData::staffList.begin();it!=CData::staffList.end();it++)//验证是否读对
		{
			cout<<(*it).getId()<<" "<<(*it).getName()<<" "<<(*it).getPwd()<<" "<<(*it).getRole()<<endl;
		}
	}
}

结果:读到的是文件中的正确信息

到此这篇关于C++文件的数据写入和文件的数据读取的方法实现的文章就介绍到这了,更多相关C++文件数据写入和读取内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++ txt 文件读取,并写入结构体中的操作

    如下所示: wang 18 001 li 19 002 zhao 20 003 代码如下: #include <string> #include <iostream> #include <fstream> using namespace std; struct people { string name; int age; string id; }p[20]; int main() { int n = 0; ifstream in( "a.txt" ,

  • c++实现逐行读取配置文件写入内存的示例

    不解析配置内容,只读取文件内容,剪去注释和首尾空格后写入缓存: vector<string> 中.供其他方法使用.代码是在做一个MFC小工具时写的. ReadProtocol.h 复制代码 代码如下: /*** 从文件中 读取 protocol 的内容 写入缓存* 供外部方法使用* Alex Liu, 2014*/ #pragma once #include <vector>#include <map>#include <list>#include <

  • c++读取和写入TXT文件的整理方法

    如下所示: #include "stdafx.h" #include <iostream> //无论读写都要包含<fstream>头文件 #include <fstream> #include <iomanip> using namespace std; int main() { //ifstream从文件流向内存的ifstream表示文件输入流,意味着文件读操作 ifstream myfile("c://a.txt"

  • 将pandas.dataframe的数据写入到文件中的方法

    导入实验常用的python包.如图2所示. [import pandas as pd]pandas用来做数据处理.[import numpy as np]numpy用来做高维度矩阵运算.[import matplotlib.pyplot as plt]matplotlib用来做数据可视化. pandas数据写入到csv文件中: [names = ['Bob','Jessica','Mary','John','Mel']]创建一个names列表[ births = [968,155,77,578,

  • pandas 把数据写入txt文件每行固定写入一定数量的值方法

    我遇到的情况是:把数据按一定的时间段提出.比如提出每天6:00-8:00的每个数据,可以这样做: # -*-coding: utf-8 -*- import pandas as pd import datetime #读取csv文件 df=pd.read_csv('A_2+20+DoW+VC.csv') #求'ave_time'这一列的平均值 aveTime=df['ave_time'].mean() #把ave_time这列的缺失值进进行填充,填充的方法是按这一列的平均值进行填充 df2=df

  • 使用ByteArrayOutputStream实现将数据写入本地文件

    目录 ByteArrayOutputStream将数据写入本地文件 那来了解一下ByteArrayOutPutStream吧 在表格输出时 FileOutputStream的写入方法 把读取的结果写入到ByteArrayOutputStream ByteArrayOutputStream将数据写入本地文件 在一个项目中做一次性校验部分,需要将校验后数据写入表格后上传.巧的是,服务器Down了.作为一个新手实习生菜鸟,为了测试自己的代码和输出结果有没有毛病,在大神同事的指点下选择了先将表格输出到本

  • 教你用python将数据写入Excel文件中

    目录 一.导入excel表格文件处理函数 二.创建excel表格类型文件 三.在excel表格类型文件中建立一张sheet表单 四.自定义列名 五.将列属性元组col写进sheet表单中 六.将数据写进sheet表单中 七.保存excel文件 附:Python读取Excel文件数据 总结 将数据写入Excel文件中,用python实现起来非常的简单,下面一步步地教大家. 一.导入excel表格文件处理函数 import xlwt 注意,这里的xlwt是python的第三方模块,需要下载安装才能使

  • python数据写入Excel文件中的实现步骤

    目录 一.导入excel表格文件处理函数 二.创建excel表格类型文件 三.在excel表格类型文件中建立一张sheet表单 四.自定义列名 五.将列属性元组col写进sheet表单中 六.将数据写进sheet表单中 七.保存excel文件 总结 将数据写入Excel文件中,用python实现起来非常的简单,下面一步步地教大家. 一.导入excel表格文件处理函数 import xlwt 注意,这里的xlwt是python的第三方模块,需要下载安装才能使用,不然导入不了(python第三方库的

  • C++文件的数据写入和文件的数据读取的方法实现

    目录 一:没有数据,准备数据,写入文件 二:读文件操作 一:没有数据,准备数据,写入文件 1.main.cpp #include<iostream> using namespace std; #include<fstream> #include<string> #include<list> #include"CData.h" #include"CStaff.h" int main() { CData::userInit

  • Nodejs处理Json文件并将处理后的数据写入新文件中

    目录 处理Json文件并将处理后的数据写入新文件 问题描述 实现过程 用Nodejs解析json数据 处理Json文件并将处理后的数据写入新文件 问题描述 事情是这样的,朋友让我处理一个json文件并将处理后的数据写入新文件.这个json文件的结构如下: [     {         "head_img": "http://wx.qlogo.cn/mmhead/xxxxxxxxxxx",         "nick_name": "x

  • Python实现的读取文件内容并写入其他文件操作示例

    本文实例讲述了Python实现的读取文件内容并写入其他文件操作.分享给大家供大家参考,具体如下: 文件目录结构,如图: read_file.py是工作文件,file_test.py是读取文件源,write_test.py是写入目标文件. 文件A:file_test.py #coding=utf-8 for i in range(1, 10): print i 文件B:read_file.py # coding=utf-8 # 打开件A f = open('./file_test.py', 'rb

  • OpenCV中的cv::Mat函数将数据写入txt文件

    在使用opencv进行图像处理的过程中,经常会涉及到将文件中的数据读入到cv::Mat中,或者将cv::Mat中的数据写入到txt文件中. 下面就介绍一种我常用的将cv::Mat中的数据写入到txt文件中的方法,具体见代码: void writeMatToFile(cv::Mat& m, const char* filename) { std::ofstream fout(filename); if (!fout) { std::cout << "File Not Opene

  • Python将列表数据写入文件(txt, csv,excel)

    写入txt文件 def text_save(filename, data):#filename为写入CSV文件的路径,data为要写入数据列表. file = open(filename,'a') for i in range(len(data)): s = str(data[i]).replace('[','').replace(']','')#去除[],这两行按数据不同,可以选择 s = s.replace("'",'').replace(',','') +'\n' #去除单引号,

随机推荐