MFC---CInfoFile類總結

.h文件如下: 

#pragma once
#pragma once

#include <list>
#include <fstream>
#include <iostream>
#include <string>


#define _F_LOGIN "./login.ini"
#define _F_STOCK "./stock.txt"

using namespace std;

struct msg
{
	int id; //商品id
	string name; //商品名
	int price; //商品價格
	int num; //商品個數
};

class CInfoFile
{
public:
	CInfoFile();
	~CInfoFile();
	//讀取登錄信息
	void ReadLogin(CString &name, CString &pwd);

	//修改密碼
	void WritePwd(char* name, char* pwd);

	//讀取商品數據
	void ReadDocline();

	//商品寫入文件
	void WriteDocline();

	//添加新商品
	void Addline(CString name, int num, int price);

	list<msg> ls;	//存儲商品容器
	int num;			//用來記錄商品個數
};

.C文件如下 :

#include"pch.h"
#include "CInfoFile.h"

CInfoFile::CInfoFile()
{
}

CInfoFile::~CInfoFile()
{
}

//讀取登錄信息
void CInfoFile::ReadLogin(CString &name, CString &pwd)
{
	ifstream ifs; //創建文件輸入對象
	ifs.open(_F_LOGIN);
	char buf[1024] = { 0 };

	ifs.getline(buf, sizeof(buf));	//讀取一行內容
	name = CString(buf);	//將char* 轉換爲CString

	ifs.getline(buf, sizeof(buf));	//讀取一行內容
	pwd = CString(buf);	//將char* 轉換爲CString

	ifs.close();	//關閉文件

}
//修改密碼
void CInfoFile::WritePwd(char* name, char* pwd)
{
	ofstream ofs; //創建文件輸出對象
	ofs.open(_F_LOGIN); //打開文件
	ofs << name << endl;	//name寫入文件
	ofs << pwd << endl;	//pwd寫入文件

	ofs.close();	//關閉文件
}
//讀取商品的信息
void CInfoFile::ReadDocline()
{
	ifstream ifs(_F_STOCK); //輸入方式打開文件
	char buf[1024] = { 0 };
	num = 0;	//初始化商品數量爲0
	ls.clear();
	//取出表頭
	ifs.getline(buf, sizeof(buf));

	while (!ifs.eof())	//沒到文件結尾
	{
		msg tmp;

		ifs.getline(buf, sizeof(buf));	//讀取一行
		num++;	//商品數量加一

		//AfxMessageBox(CString(buf));
		char *sst = strtok(buf, "|");	//以"|"分隔
		if (sst != NULL)
		{
			tmp.id = atoi(sst);	//商品id
		}
		else
		{
			break;
		}

		sst = strtok(NULL, "|");
		tmp.name = sst;	//商品名稱

		sst = strtok(NULL, "|");
		tmp.price = atoi(sst);	//商品價格

		sst = strtok(NULL, "|");
		tmp.num = atoi(sst);	//商品數目

		ls.push_back(tmp);	//放在鏈表的後面
	}

	ifs.close();	//關閉文件

}
//商品寫入文件
void CInfoFile::WriteDocline()
{
	ofstream ofs(_F_STOCK); //輸出方式打開文件
	string bt = "商品ID | 商品名 | 單價 | 庫存";
	if (ls.size() > 0)	//商品鏈表有內容才執行
	{
		ofs << bt << endl;	//寫入表頭

		//通過迭代器取出鏈表內容,寫入文件,以"|"分割,結尾加換行
		for (list<msg>::iterator it = ls.begin(); it != ls.end(); it++)
		{
			ofs << it->id << "|";
			ofs << it->name << "|";
			ofs << it->price << "|";
			ofs << it->num << endl;
		}
	}
	ofs.close();

}
//添加新商品
//name:商品名稱,num:庫存,price:價格
void CInfoFile::Addline(CString name, int num, int price)
{
	msg tmp;
	if (ls.size() > 0)
	{
		//商品名稱,庫存,價格有效
		if (!name.IsEmpty() && num > 0 && price > 0)
		{
			tmp.id = ls.size() + 1;	//id自動加1
			CStringA str;
			str = name;					//CString 轉CStringA
			tmp.name = str.GetBuffer();//CString 轉爲char *, 商品名稱
			tmp.num = num;			//庫存
			tmp.price = price;		//價格

			ls.push_back(tmp);			//放在鏈表的後面
		}
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章