gpt4 book ai didi

c++ - 同时读取两个不同的文件

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:06 25 4
gpt4 key购买 nike


我有 2 个文件,我希望每个核心读取自己的文件(每个文件有 5 行)并显示其内容
在此代码中,我有 2 个核心(core0、core1),输出核心 0 读取 core1 的内容(5 行)。 core1 从他的内容中读取了 4 行。

我试着让它好像其他条件一样,每个文件都有自己的阅读器,但同样的问题仍然存在。我该怎么办?

    #include <vector>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#include <omp.h>
#include <fstream>
#include <iostream>
using namespace std;


void func2(int CoreID )
{

int iFace;
int iFaces=0;
if (CoreID==0)
{
FILE* imgListFile = 0;
char imgFilename[5012];
char actualPath[90]="C:\\DaliaDaliaSh\\TrainingFiles\\File10img_0_C";
strcat(actualPath , "0.txt");
imgListFile= freopen(actualPath , "r",stdin);
while (fgets(imgFilename, 5012, imgListFile))
{
++iFaces;
printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename );

}
rewind(imgListFile);
}
else if (CoreID==1)
{
FILE* imgListFile2 = 0;
char imgFilename2[5012];
char actualPath2[90]="C:\\DaliaDaliaSh\\TrainingFiles\\File10img_0_C";
strcat(actualPath2 , "1.txt");
imgListFile2= freopen(actualPath2 , "r",stdin);
while (fgets(imgFilename2, 5012, imgListFile2))
{
++iFaces;
printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename2 );

}
rewind(imgListFile2);
}


//printf ("*ID = %d open actualPath= %s\n" , myId , actualPath);


printf("core %d , iFaces= %d \n", CoreID , iFaces);
}
void main(int argc,char **argv)
{
MPI::Init(argc,argv);
int threadnum=2;
omp_set_num_threads(threadnum);

#pragma omp parallel
{

int CoreID = omp_get_thread_num();
int x ;

func2(CoreID);

cout <<"@@@@after call func inside pragma \n" ;

}


MPI ::Finalize();
}

最佳答案

您正在 stdin 上执行 freopen。因此,两个核心将使用相同的流,并且文件读取将取决于哪个核心首先/最后打开流[这是一个竞争条件]。

改为执行常规的fopen,它们就不会发生冲突[就像他们现在所做的那样]

关于c++ - 同时读取两个不同的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34847406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com