I want to know how to load data from a text file into shared memory in C or C++. I want to assign the content of the file into structs line-by-line, like:
name: gaimi dancer id: 443432 address: 123 Southbrook Dr. Mombai, In PhoneNumber: 8876549300
and so on with the whole file, and then load these structs into shared memory.
I have tried everything but nothing worked. I have tried strcpy()
and memcpy()
and they did not work.
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;
}
text.txt
gaimi dancer 443432 123 Southbrook Dr. Mombai, In 8876549300 Yall S Player 465387 543 Saif Rd. Manama, BA 7665647833 Dean Rama 456339 908 Sea Ave. Manama, BA 4556748900 Maya Rab 677032 654 South 3rd St. Kwait, KW 3425435456 Patricia Carey 547839 320 Old navy St. Chiacgo, IL 1112332534