Sara
Sara

Reputation: 125

C++ Read from file with shared memory

I wrote 2 programs ,the first one make shared memory with two variables for the character and string size.And the other program is read the shared variables.

My problem : I try to make my programs to read all words in the text file , but i can't to do it so i made my programs to read 1 word.How i can make it for all words in file.

Upvotes: 1

Views: 1204

Answers (1)

user4581301
user4581301

Reputation: 33932

To read t he file, this region

if (file1.is_open())
{
     file1>> word;//read word from file to know size of word $$ read first char into shm ->str
     shm->size=word.length();
     strcpy(str2, word.c_str());
     shm ->str=str2[0];
     file1<<"             ";
 }

Should be more along the lines of

while(file1>> word)
{
     shm->size=word.length();
     shm ->str=word[0];
 }

I got rid of the strcpy as it didn't seem to be needed, and the file1<<" "; because only pain can come from trying to write to an ifstream. By default the file backed by ifstream has been opened for read only and cannot be written. If it must be written use fstream and specify std::fstream::in | std::fstream::out on the open call. You will probably want to think carefully about how you intend to write to the file while you are reading it.

Currently shm will be overwritten by every word found. This is probably not what you want. I suspect you're after something more like:

  1. open file
  2. wait for turn
  3. read from file
  4. update shmem
  5. set other's turn
  6. goto 2

Something like

sharedBoundary->turn==0

file1.open ("file1.txt");
while(file1>> word)
{
     while(sharedBoundary->turn==1);
     shm->size=word.length();
     shm ->str=word[0];
     sharedBoundary->turn=1;     
}

I don't see the point for both sharedBoundary flag and turn unless there is much more significant guard logic we aren't shown, so I dropped the flag to simplify the example. My usage of may be incorrect, so adapt to taste.

Program 2. In order to synchronize with Program 1, you need something like this:

sharedBoundary->turn==0
while(/* unspecified termination logic */)
{
    while(sharedBoundary->turn==0);
    cout<<"The new values stored in the shared memory:\n";
    cout<<"Text="<<shm ->str<<"\nSize="<<shm->size<<"\n";
    PrintCharNtimes(shm ->str, shm->size);
    sharedBoundary->turn=0;     
}

Upvotes: 1

Related Questions