一、從一個文本文件讀入首空閑塊和空閑塊數,格式如下(要求最多32行)
21 20
41 10
53 5
……
其中一行要求有兩個數
二、從讀入的數中判斷有沒有上下鄰塊,如果有要進行合併(回收)。
三、輸出回收過的空閑塊。(我的理解是不應該有相鄰的塊存在,因爲已經經過合併了)
程序比較簡單,我的做法可能有的地方欠妥,歡迎大家指正,謝謝
(日文系統.net 2003中調試通過:)
- #include "stdafx.h"
- typedef struct FreeBlock
- {
- int firstBlock; //首空閑塊塊號
- int count; //空閑塊數
- }FreeBlock;
- /**************空閑塊讀入****************/
- int inputFromFile(FreeBlock *tables)
- {
- int i = 0,j;
- char strTem[20],strNum[20],strFile[256],*p,*q;
- printf("請輸入文件名:");
- scanf("%s",strFile);
- FILE *file = fopen(strFile,"r");
- if(file==NULL)
- {
- printf("輸入的文件%s不存在/n",strFile);
- return -1;
- }
- while(!feof(file)&&i<32)//空閑塊數最大32個
- {
- p = strTem;
- fgets(p,20,file);//一次讀入整行數據
- for(j=0;j<1 && (q = strchr(p,' '));j++) //文件分割符為空格
- {
- memset(strNum,0,sizeof(strNum)*sizeof(char));
- strncpy(strNum,p,q-p);
- (&tables[i])->firstBlock = atoi(strNum); //一行僅存首空閑塊和空閑塊數
- p=q+1;
- }
- (&tables[i])->count = atoi(p);
- i++;
- }
- fclose(file);
- return 0;
- }
- /**************空閑塊回收****************/
- int reclaimBlock(FreeBlock *tables)
- {
- int i,j;
- for(i=1;i<32;i++)
- {
- for(j=0;j<=i;j++)
- {
- //上鄰空閑塊
- if((&tables[i])->firstBlock + (&tables[i])->count == (&tables[j])->firstBlock)
- {
- //覆蓋上鄰
- (&tables[i])->count += (&tables[j])->count;
- (&tables[j])->firstBlock = 0;
- (&tables[j])->count = 0;
- }
- //下鄰空閑塊
- if((&tables[i])->firstBlock == (&tables[j])->firstBlock + (&tables[j])->count)
- {
- (&tables[j])->count += (&tables[i])->count;
- //覆蓋下鄰
- (&tables[i])->firstBlock = 0;
- (&tables[i])->count = 0;
- }
- }
- }
- return 0;
- }
- /**************初始化****************/
- void init(FreeBlock *tables)
- {
- int i=0;
- while(i<32)
- {
- (&tables[i])->firstBlock = 0;
- (&tables[i])->count = 0;
- i++;
- }
- }
- /**************空閑塊顯示****************/
- void displayBlock(FreeBlock *tables)
- {
- int i,j=0;
- printf("空閑塊首塊號 空閑塊個數/n");
- for(i=0;i<32;i++)
- {
- if((&tables[i])->firstBlock!=0)
- printf("%8d%8d/n",(&tables[i])->firstBlock,(&tables[i])->count);
- else
- j++;
- }
- for(i=0;i<j;i++)
- printf("%8d%8d/n",0,0);
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- int i=0;
- FreeBlock freeTables[32]; //空閑塊
- init(freeTables);//初始化
- //讀入文件
- i = inputFromFile(freeTables);
- if(i==-1)//輸入錯誤
- {
- system("pause");
- return -1;
- }
- //回收空閑塊
- reclaimBlock(freeTables);
- //顯示空閑塊
- displayBlock(freeTables);
- system("pause");
- return 0;
- }