1、页面置换模拟
模拟页置换算法,统计缺页率。
#include<stdio.h>
#include<windows.h>
#define MemCapacity 3
int pageInMainMem(int page, int mainMem[], int MainCapacity);
void foldPage(int page, int mainMem[], int MainCapacity);
void main()
{
int pageDirection[] = { 4,3,2,1,4,3,5,4,3,2,1,5 }, pageNum = 12;
int mainMem[MemCapacity] = { 0 };
int RequestCount = 0, Request = 0;
int i, j;
printf("时间 访问页 内存状态 缺页中断 调入页\n");
for (i = 0; i < pageNum; i++)
{
printf("%3d ", i);
printf(" %2d ", pageDirection[i]);
Request = 0;
if (pageInMainMem(pageDirection[i], mainMem, MemCapacity) == -1)
{
foldPage(pageDirection[i], mainMem, MemCapacity);
RequestCount++;
Request = 1;
}
for (j = 0; j < MemCapacity; j++)
printf("%2d ", mainMem[j]);
if (Request == 1)
{
printf(" + ");
printf(" %d", pageDirection[i]);
}
printf("\n");
}
printf("缺页中断次数=%d\n", RequestCount);
printf("缺页率=%d/%d=%.2f%%\n", RequestCount, pageNum, (float)RequestCount / pageNum * 100);
Sleep(10000);
}
int pageInMainMem(int page, int mainMem[], int MainCapacity)
{
int i;
for (i = 0; i < MainCapacity; i++)
{
if (page == mainMem[i])
{
return i;
}
return -1;
}
}
void foldPage(int page, int mainMem[], int MainCapacity)
{
int i;
for (i = MainCapacity - 1; i > 0; i--)
mainMem[i] = mainMem[-1];
mainMem[0] = page;
}
结果:
实践24 文件操作
(1)创建h1.txt文件,并向文件h1.txt写入数据,然后读出写入到文件h1.txt中的数据。
(2)将文件h1.txt复制为文件h2.txt,然后删除文件h2.txt。
#include<windows.h>
#include<stdio.h>
int main()
{
HANDLE hFile{};
DWORD szBuffer[5];
const char szText[] = "文件操作测试!";
int Len;
char chBuffer[100];
LONG lDistance = 0;
DWORD dwReadSize = 0;
int userSel;
do {
printf("\n\n----------------文件操作----------------\n");
printf("1-------创建h1.txt文件\n");
printf("2-------写入h1.txt文件\n");
printf("3-------从h1.txt中读取数据\n");
printf("4-------h1.txt复制为h2.txt文件\n");
printf("5-------删除h2.txt文件\n");
printf("6-------退出\n请输入选择:\n\n");
scanf_s("%d", &userSel);
switch (userSel)
{
case 1:
hFile = CreateFile("C:\\h1.txt", GENERIC_WRITE |
GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
printf("文件已经创建成功!\n");
break;
case 2:
Len = lstrlen(szText);
WriteFile(hFile, szText, Len, szBuffer, NULL);
FlushFileBuffers(hFile);
printf("文件写入成功!\n");
break;
case 3:
SetFilePointer(hFile, lDistance, NULL, FILE_BEGIN);
ReadFile(hFile, chBuffer, 14, &dwReadSize, NULL);
chBuffer[dwReadSize] = '\0';
printf("文件读取成功,文件内容为:%s\n,chBuffer");
break;
case 4:
CopyFile("C:\\h1.txt", "C:\\h2.txt", FALSE);
printf("文件复制成功!\n");
break;
case 5:
DeleteFile("C:\\h2.txt");
printf("文件删除成功!\n");
break;
case 6:
printf("退出\n");
break;
default:
printf("选择错误!\n");
break;
}
} while (userSel != 6);
CloseHandle(hFile);
return 0;
}
使用VS2022运行会出现以下错误:
解决方法:
在项目属性->高级->字符集,把字符集设为“未设置”
结果: