上一篇中,我們講了如何自己定義一個(gè)負(fù)責(zé)文件操作的功能集合,今天我們就利用這一組功能完成保存記錄的動(dòng)作。
文件讀寫操作
在上一篇的基礎(chǔ)上,我們稍作修改加入到我們的通訊錄工程中來。代碼如下:
-
MyFile.h
#ifndef __MY_FILE_H__ #define __MY_FILE_H__ #include <stdio.h> #define FOR_READ 0 #define FOR_WRITE 1 FILE* fp; extern int OpenFile(char* pFileName, int nOperate); extern void CloseFile(); extern char* ReadLine(); extern int WriteLine(char* pLine); #endif -
MyFile.c
#include "MyFile.h" #include "string.h" #define BUF_SIZE 100 char pBuf[BUF_SIZE]; int OpenFile(char* pFileName, int nOperate) { switch (nOperate) { case FOR_READ: fp = fopen(pFileName, "r"); break; case FOR_WRITE: fp = fopen(pFileName, "w+"); break; default: break; } if (fp == NULL) { return 0; } else { return 1; } } void CloseFile() { fflush(fp); fclose(fp); } char* ReadLine() { pBuf[0] = 0; if(feof(fp)) { return NULL; } else { if (NULL == fgets(pBuf, BUF_SIZE, fp)) { return NULL; } else { pBuf[strlen(pBuf) - 1] = 0; } } return pBuf; } int WriteLine(char* pLine) { fwrite(pLine, sizeof(char), strlen(pLine), fp); fwrite("\n", sizeof(char), 1, fp); return 1; }
注意,這段代碼和上一篇中的有所不同,主要是我們?cè)赗eadLine()函數(shù)的實(shí)現(xiàn)中采用了fgets()這個(gè)函數(shù)。這個(gè)函數(shù)的特點(diǎn)是讀取字符串時(shí)遇到換行符會(huì)自動(dòng)停止,與我們的需求比較類似。
數(shù)據(jù)保存功能
當(dāng)我們?cè)诔绦蛑袖浫肓艘恍┩ㄓ嶄洍l目之后,我們需要在退出前將這些數(shù)據(jù)保存在文件中。在main.c文件中,我們添加一個(gè)函數(shù)調(diào)用,函數(shù)名是SavedRecords()。

這個(gè)函數(shù)實(shí)現(xiàn)如下:
void SavedRecords()
{
if (OpenFile("book.txt", FOR_WRITE) != 1)
{
return;
}
ListNode* pNode;
for (pNode = g_pL; pNode->_pR != NULL; pNode = pNode->_pNext)
{
pNode->_pR;
WriteLine(pNode->_pR->_pStrName->pBuf);
WriteLine(pNode->_pR->_pStrTel->pBuf);
WriteLine(pNode->_pR->_pStrPS->pBuf);
WriteLine("----------");
}
CloseFile();
}
這個(gè)函數(shù)主要執(zhí)行三個(gè)動(dòng)作:
- 打開一個(gè)名為book.txt的文件,注意使用寫模式打開
- 遍歷鏈表,之后調(diào)用WriteLine()函數(shù)把每條記錄的每個(gè)條目寫入book.txt文件
- 關(guān)閉文件
在文件中保存數(shù)據(jù)時(shí),我們用“-----”來分隔不同的記錄。就這樣,數(shù)據(jù)保存功能實(shí)現(xiàn)了。
數(shù)據(jù)恢復(fù)功能
保存了數(shù)據(jù)之后,在每次啟動(dòng)程序時(shí),需要重新把這些數(shù)據(jù)讀取出來保存進(jìn)數(shù)據(jù)鏈表中。我們用一個(gè)函數(shù)LoadRecords()來實(shí)現(xiàn)。

在圖中程序啟動(dòng)的位置,加入這個(gè)函數(shù)的調(diào)用。具體代碼如下:
void LoadRecords()
{
Record* pR = NULL;
if (OpenFile("book.txt", FOR_READ) != 1)
{
return;
}
char* pLine = NULL;
while ((pLine = ReadLine()) != NULL)
{
if (pLine[0] == 0)
{
break;
}
RecordInit(&pR);
RecordSetName(pR, pLine);
pLine = ReadLine();
RecordSetTel(pR, pLine);
pLine = ReadLine();
RecordSetPS(pR, pLine);
pLine = ReadLine();
ListAdd(pR);
}
CloseFile();
}
這段代碼也很簡(jiǎn)單,通過文件操作接口把book.txt文件中的數(shù)據(jù)讀出,填進(jìn)Record數(shù)據(jù)結(jié)構(gòu),之后添加到數(shù)據(jù)鏈表中。此時(shí),執(zhí)行查找方法打印出全部的數(shù)據(jù),看看是不是之前的數(shù)據(jù)都被恢復(fù)了呢?
這樣,我們一個(gè)完整的項(xiàng)目就完成了。
完整的代碼請(qǐng)?jiān)谙旅孢@個(gè)路徑中獲取:https://github.com/breakerthb/TelBook.git
我是天花板,讓我們一起在軟件開發(fā)中自我迭代。
如有任何問題,歡迎與我聯(lián)系。
上一篇:21天C語(yǔ)言代碼訓(xùn)練營(yíng)(第十五天)
下一篇:21天C語(yǔ)言代碼訓(xùn)練營(yíng)(第十七天)