2013-03-08 42 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]等。所有行都分隔开来,并以空字符结尾。