当我的代码在mpi结构时,我在c++ (visual 2010)中读取和编写文本文件有一些问题。我不知道如何打开文件(文本文件)并阅读它们。请介绍一个示例代码与文本文件来完成这项工作....谢谢你。
this id my code:
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <mpi.h>
#include <iostream>
#include <fstream>
using namespace std;
const int iMax = 121;
const int jMax = 35;
const int N=2;
const int BBx = (iMax-1)/N;
struct S_cell{
double xc, yc;
}cell[BBx+1][jMax];
int main(int argc ,char *argv[] )
{
int mpi_rank ,mpi_size;
MPI_Init(&argc ,& argv);
MPI_Comm_size(MPI_COMM_WORLD , & mpi_size);
MPI_Comm_rank(MPI_COMM_WORLD , & mpi_rank);
int i,j;
double XXX, YYY;
fstream grid;
grid.open("Grid.plt");
for(int j=0; j<jMax; j++)
for(int i=0+BBx*mpi_rank; i<(mpi_rank+1)*BBx+1; i++)
{
grid>>XXX>>YYY;
cell[i-mpi_rank*BBx][j].xc = XXX;
cell[i-mpi_rank*BBx][j].yc = YYY;
}
j=10;
for(int i=0+BBx*mpi_rank; i<(mpi_rank+1)*BBx+1; i++)
cout<<cell[i-mpi_rank*BBx][j].yc<<" "<<mpi_rank<<endl;
MPI_Finalize();
}
在MPI代码中读取文件与正常情况相同,但是每个进程都会尝试读取文件。典型的用例是每个流程有一个输入文件。举个例子,假设我们正在运行进程(mpirun -np 4 ./exe
)。然后我们将有四个输入文件,比如:
input_0.txt
input_1.txt
input_2.txt
input_3.txt
要读取main中的文件,执行以下操作:
int main (int argc, char **argv)
{
int myrank = 0;
MPI_Comm comm = MPI_COMM_WORLD;
// Initialize MPI and get the process rank
MPI_Init(&argc, &argv);
MPI_Comm_rank(comm,&myrank);
// Build the filename for the given process
std::string filename = "input_" + myrank + ".txt";
// Open the file stream and read or write
std::ifstream in(filename.c_str());
read_file(in);
in.close();
// Finalize MPI and exit
MPI_Finalize();
return 0;
}
一些注意事项:
- 我的理解是,新的MPI标准已经弃用了c++绑定,所以最好使用C MPI接口。
- 如果你想让所有进程从同一个文件中读取不同的信息,那么你的' read_file '函数需要正确地处理这个问题,这将更加复杂。
- 让多个进程读取同一个文件是完全可以的,只要它们不修改它。
- 单个文件的并行I/O通常通过使用库来实现(谷歌"MPI并行I/O"等)。