2014-10-27 84 views
1

我應該在固定長度的記錄和字段的數據文件中讀取,在內存中創建一個排序索引列表,該列表保存到一個文件。然後,我將編寫第二個程序(通過Linux命令行)交互式地獲取一個鍵和索引文件名,打開並加載索引文件,使用索引表搜索給定的鍵,然後打開並返回正確的數據記錄。創建和訪問索引文件在C++

原始文件由記錄用鑰匙(INT),一個名稱(最多8個字符的字符串),代碼(int)和成本(雙)名單。

的RRN(相對記錄號)從1開始,在0的RRN表示與僅在第一條目的尺寸的僞記錄。

這是我將要使用的數據文件。

8 blank 0 0.0 
12345 Item06 45 14.2 
12434 Item04 21 17.3 
12382 Item09 62 41.37 
34186 Item25 18 17.75 
12165 Item16 30 7.69 
16541 Item12 21 9.99 
21212 Itme31 19 8.35 
41742 Item14 55 12.36 

執行應該在命令行以下面的方式工作在Linux中:

search 12382 prog5.idx 

與prog5.idx正在創建的索引文件。

我有一些代碼編寫的,但到目前爲止,它所有打開的數據文件。

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() { 
    ifstream data; 
    data.open("prog5.dat"); 
    ofstream outFile("prog5.idx", ios::out); 

    //if file can't be opened, exit 
    if(!data) { 
     cerr << "Open Failure" << endl; 
     exit(1); 
    } 
    else { 
     cout << "File is open" << endl; 
    } 
} 

「文件是打開」一旦我弄清楚什麼做一旦文件被打開的部分將被替換,只是使用該消息以驗證它打開該文件。

我從來沒有與這些類型的文件前,工作等有不知道在哪裏何去何從。

+0

是學校作業嗎?你可以在C++標準庫中使用容器嗎?在情況下,你可以使用'STD:map'用'STD:對'其中'Record'是一個簡單的'struct'在一行中的信息.. – gmas80 2014-10-27 23:05:55

+0

我相信是這樣,我與C++庫雖然經驗0 。 – 2014-10-27 23:06:54

回答

1

我將爲您提供一個可能的天真草案的第一個程序,讓您可以瞭解大致的構想:

#include <map> 
#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 

using namespace std; 

struct Record 
{ 
    int key; 
    char name[8]; 
    int code; 
    double cost; 
    size_t offset; 
}; 

int main() { 
    std::map<int,Record> mymap; 
    ifstream data; 
    size_t offset_count = 0; 
    data.open("prog5.dat"); 
    ofstream outFile("prog5.idx", ios::out); 

    //if file can't be opened, exit 
    if(!data) { 
     cerr << "Open Failure" << endl; 
     exit(1); 
    } 
    else { 
     cout << "File is open" << endl; 
    } 

    std::string line; 
    while (std::getline(data, line)) 
    { 
     std::istringstream iss(line); 
     Record tmp; 
     if (!(iss >> tmp.key >> tmp.name >> tmp.code >> tmp.cost)) 
     { 
      break; // error, do something 
     } 
     tmp.offset = offset_count; 
     offset_count += sizeof(Record); 
     mymap.insert(pair<int,Record>(tmp.key,tmp)); 
    } 

    // Now you have all the info (and much more) you need in memory, 
    // thus serialize the key and its position on a file 
    // So you have done the first part of the assignment 

} 

看一下例子here,如果你不知道如何遍歷在std:map之內。

+0

這看起來不錯,謝謝一堆。一個問題,「//序列化密鑰及其在文件上的位置」,我該怎麼做? – 2014-10-27 23:46:49

+1

您可以決定將索引信息寫入文本或二進制文件中。這將更改如何恢復文件索引內容。有用的答案:http://stackoverflow.com/a/12935205/2741329和http://stackoverflow.com/a/14413863/2741329 – gmas80 2014-10-27 23:55:39

+0

感謝您的幫助和鏈接。很有幫助 :) – 2014-10-28 01:49:23