C ++从具有共享内存的文件中读取

时间:2015-05-16 06:33:01

标签: c++

我写了2个程序,第一个用共享内存和两个变量作为字符和字符串大小。另一个程序是读取共享变量。

我的问题:我尝试让我的程序读取文本文件中的所有单词,但我不能这样做,所以我让我的程序读取1个单词。如何可以为文件中的所有单词创建它。

1 个答案:

答案 0 :(得分:1)

要读取文件,此区域

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<<"             ";
 }

应该更加符合

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

我摆脱了strcpy,因为它似乎并不需要,file1<<" ";因为只有痛苦可以来自尝试写入ifstream。默认情况下,ifstream支持的文件已打开以供只读,无法写入。如果必须编写,请在公开调用中使用fstream和specify std::fstream::in | std::fstream::out。您可能需要仔细考虑在阅读文件时打算如何写入文件。

目前shm将被发现的每个单词覆盖。这可能不是你想要的。我怀疑你的事情更像是:

  1. 打开文件
  2. 等待回合
  3. 从文件中读取
  4. 更新shmem
  5. 设置另一个
  6. 转到2
  7. 这样的东西
    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;     
    }
    

    我没有看到sharedBoundary标志和转向的重点,除非我们没有显示更多重要的保护逻辑,所以我放弃了标志以简化示例。我的用法可能不正确,所以要适应口味。

    程序2.为了与程序1同步,你需要这样的东西:

    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;     
    }
    
相关问题