majid
majid

Reputation: 11

read and write in mpi c++ visual 2010

I have some problem in reading and writing text files in c++ (visual 2010) when my code is in mpi structure. I dont know how open files (text files) and read them. please introduce an example code with text file that do this work .... thank you.

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();

}

Upvotes: 1

Views: 1783

Answers (1)

Mosby
Mosby

Reputation: 1341

Reading files in an MPI code is the same as normal, however each process will attempt to read the file. A typical use case is to have one input file for each process. As an example, let's say we are running on for processes (mpirun -np 4 ./exe). Then we would have four input files, say:

input_0.txt
input_1.txt
input_2.txt
input_3.txt

To read the files in main do the following:

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

Some notes:

  • My understanding is that the new MPI standard has deprecated the C++ bindings, so it is best to use the C MPI interface.
  • If you want all processes to read different information from the same file, then your `read_file` function needs to handle this properly and will be more complex.
  • It is perfectly fine to have multiple processes reading the same file, so long as they are not modifying it as well.
  • Parallel I/O to a single file is typically implemented by using a library (Google "MPI parallel I/O", etc.).

Upvotes: 1

Related Questions