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