作業系統實驗8 採用快取記憶體實現檔案讀寫
阿新 • • 發佈:2020-12-18
技術標籤:課程學習記錄
實驗8 採用快取記憶體實現檔案讀寫
一、實驗目的
(1)瞭解windows系統檔案快取記憶體的概念。
(2)熟悉windows系統檔案讀寫相關API。
(3)掌握採用緩衝方式實現檔案讀寫相關引數的設定。
二、實驗準備
CreateFile( ) 檔案建立:用於建立一個新檔案,如果檔案已經存在,則得到該檔案的控制代碼。採用快取記憶體進行檔案操作,引數dwFlagsAndAttiibutes選用FILE_FLAG_SEQUENT_SCAN。 Readfile( ) 讀檔案:從檔案指標指示的位置開始讀取檔案中的資料 WriteFile ( ) 寫檔案:將資料寫入檔案 CloseHandle() 關閉檔案控制代碼:關閉與檔案相關的控制代碼,其作用與釋放動態申請的記憶體空間類似, 這樣可以釋放系統資源,使程序安全執行。
三、實驗內容
(一)實驗內容
建立一個函式,使用該函式將原始檔source.txt中的內容讀出,再寫到目標檔案sequential.txt中去。
(二)主要程式碼
// zuoye08.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "zuoye08.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__ ;
#endif
DWORD BufferSize=1024;
char buf[1024];
/
// The one and only application object
CWinApp theApp;
using namespace std;
void FileReadWrite_Overlapped(char *source,char *destination);
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{ int nRetCode=0;
printf("Call FileReadWrite_Overlapped!\n" );
//呼叫FileReadWrite_Overlapped(char *source,char *destination)函式
FileReadWrite_Overlapped("source.txt","sequential.txt");
return nRetCode;
}
void FileReadWrite_Overlapped(char *source,char *destination)
{ HANDLE handle_src,handle_dst;
DWORD NumberOfByteRead,NumberOfByteWrite;
bool cycle;
char *buffer;
buffer=buf;
//建立檔案source.txt
handle_src=CreateFile(source,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
//採用快取記憶體進行檔案操作,引數dwFlagsAndAttiibutes選用FILE_FLAG_SEQUENT_SCAN。
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
//建立檔案sequential.txt
handle_dst=CreateFile(destination,
GENERIC_WRITE,
NULL,
NULL,
CREATE_ALWAYS,
NULL,
NULL);
//判斷檔案是否建立失敗,若失敗列印輸出提示資訊並退出
if (handle_src==INVALID_HANDLE_VALUE||handle_dst==INVALID_HANDLE_VALUE)
{
printf("File Create Fail!\n");
exit(1);
}
cycle=true;
while (cycle)
{
NumberOfByteRead=BufferSize;
//讀取檔案source.txt
if (!ReadFile(handle_src,buffer,NumberOfByteRead,& NumberOfByteRead,NULL))
{
//讀取檔案source.txt失敗
printf("read File Error! %d\n",GetLastError());
exit(1);
}
if(NumberOfByteRead<BufferSize) cycle=false;
//寫入檔案sequential.txt
if(!WriteFile(handle_dst,buffer,NumberOfByteRead,&NumberOfByteWrite,NULL))
{
寫入檔案sequential.txt失敗
printf("Write File Error! %d\n",GetLastError());
exit(1);
}
}
//關閉檔案控制代碼("source.txt","sequential.txt")
CloseHandle(handle_src);
CloseHandle(handle_dst);
}
四、實驗結果與總結
本實驗與實驗七無緩衝方式實現檔案讀寫大體上一致,但是由於要採用快取記憶體進行檔案操作,在使用函式
Createfile()建立檔案時,其引數dwFlagsAndAttiibutes應選用FILE_FLAG_SEQUENT_SCAN。
一開始成功執行程式沒有source.txt檔案,後找到原因,即在建立檔案source.txt語句中dwCreationDisposition
引數為OPEN_EXISTING,即開啟已存在檔案,若檔案不存在,則該函式開啟失敗。所以首先應該手動建立source.txt檔案,
之後在source.txt中新增些文字資訊如“實驗8 採用快取記憶體實現檔案讀寫”程式執行完後,開啟sequential.txt,
發現其內容和source.txt中內容完全一致,如下圖所示。
該實驗完成快取記憶體方式的檔案讀寫操作。先建立兩個檔案,即source.txt和sequential.txt,
然後反覆從檔案source.txt中讀出資料塊,並寫到檔案sequential.txt中去,直到檔案尾為止。