我试图读取一个文件,并将每行放入共享内存(是的,我知道这不是最实际的做法,但让我只是说我必须使用共享内存)。是否可以将这些行读入共享内存中,以便我可以快速跳转到共享内存中的某一行?可能将字符串读入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);
}