【发布时间】:2020-08-30 19:37:43
【问题描述】:
我想知道如何将文本文件中的数据加载到 C 或 C++ 中的共享内存中。我想将文件的内容逐行分配到结构中,例如:
名称:gaimi舞者 编号:443432 地址:123 Southbrook Dr. Mombai, In 电话号码:8876549300整个文件以此类推,然后将这些结构加载到共享内存中。
我已经尝试了一切,但没有任何效果。我试过strcpy() 和memcpy() 都没有用。
reader.cpp
#include <sys/shm.h>
#include <stdio.h>
#include<string>
#include<cstring>
#include<cstdlib>
using namespace std;
struct Stu_Info{
char name[30];
char id[20];
char address[30];
char PhoneNumber[20];
};
int main()
{
// ftok for generating unique key
key_t key = ftok("shm",6556);
// shmget returns an identifier in shmid
id = shmget(key,1024*4,0666|IPC_CREAT);
//to make sure the shm made correctly
if (id < 0){
perror("create: shmget failed");
exit(1);
}else{
cout << "The shm was craeted!!";
}
// shmat to attach to shared memory
char *str = (char*) shmat(id,(void*)0,0);
cout<<"Write Data : ";
gets(str);
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
writer.cpp
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int id = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(id,(void*)0,0);
printf("Data read from memory: %s\n",str);
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(id,IPC_RMID,NULL);
return 0;
}
文本.txt
gaimi舞者 443432 123 Southbrook 孟买博士,在 8876549300 雅尔 S 播放器 465387 赛义夫路 543 号麦纳麦,文学士 7665647833 院长拉玛 456339 908 Sea Ave. 麦纳麦,BA 4556748900 玛雅拉布 677032 654 South 3rd St. Kwait, KW 3425435456 帕特里夏·凯莉 547839 320 Old navy St. Chiacgo, IL 1112332534【问题讨论】:
-
显示当时不起作用的代码,包括任何错误。这不是代码编写服务。如果你搜索“serializing in C++”,你会发现很多资源。
-
您应该将 same
id传递给shmget以便能够共享>一个片段。顺便说一句,为什么不改用mmap,哪个更现代、更容易?见here -
您是否在 *nix 环境中运行? shm 调用在 Windows 中不能很好地工作
-
我在 linux 上运行 cpp。我试过这段代码,但没有用。
标签: c++ c synchronization shared-memory file-handling