2013-03-08 67 views
1

我試圖讀取一個文件,並將每行放入共享內存(是的,我知道這不是最實際的做法,但讓我只是說我必須使用共享內存)。是否可以將這些行讀入共享內存中,以便我可以快速跳轉到共享內存中的某一行?可能將字符串讀入C中的共享內存?

例如,如果我的文件是:

ABCD 
EFGH 
IJKL 

我能直接跳轉到共享內存中3'rd線,使我得到「IJKL」?

我目前正在讀入內存這樣的:

key_t key; /* key to be passed to shmget() */ 
    int shmflg; /* shmflg to be passed to shmget() */ 
    int shmid; /* return value from shmget() */ 
    int size; /* size to be passed to shmget() */ 
    char *shm, *s; 

// we'll name our shared memory segment: 1234 
    key = 1234; 
    if((shmid = shmget(key,size, S_IRUSR | S_IWUSR)) < 0){ 
     perror("shmget failed"); 
     exit(1); 
    } 

    // attach the segment to our data space 
    if((shm = shmat(shmid, NULL, 0)) == (char*) -1){    
     perror("shmat failed"); 
     exit(1); 
     } 
    s = shm; 

    // note: line is a character array that's large enough to include the whole file 
    while(fgets(line, 128, fp) != NULL){    
    // try putting the line into our shared memory: 
    sprintf(s, line); 
    }   

回答

2

有幾種方法可以做到這一點。您可以使用隊列或字符串數​​組。我會告訴你如何使用字符串數組來完成它,因爲它可能是一個更簡單的概念。

首先,您需要文件的大小和文件中的行數。我會讓你知道如何做到這一點。

file_sizeline_count排序後,您將分配一個大小爲file_size + line_count + (line_count + 1) * sizeof(char *)的共享內存空間,以便存儲我們需要共享的所有信息。

聲明一個變量char **index並將其設置爲index = (char **)shm定義的共享內存塊的開始是我們線指標,並設定index[line_count] = NULL讓你知道後,當你index[n]返回NULL它,因爲你已經走到了盡頭。

聲明一個變量char *bufferindex終止於後馬上所以現在我們有buffer它設置爲buffer = (char *)(&index[line_count+1])指向本地內存塊的地方。它將在哪裏存儲線路。

現在讀這樣的臺詞:

int i = 0; 
while(!feof(fp)) { 
    index[i++] = buffer; 
    fgets(buffer, file_size, fp); 
    buffer += strlen(buffer) +1; 
} 

一旦其完成讀取文件時,你擁有這一切在index組織。第一行是index[0],第二行是index[1]等。所有行都分隔開來,並以空字符結尾。