MPI_File_read Error

2019-04-17 07:08发布

问题:

I am trying to use MPI_File_read to read from an input file. But it is not correctly reading the values. Here is my input file:

11 3 4 5 2

And here is the code i am using to try to read it:

char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
MPI_File_read(f, &n, 1, MPI_INT, &status);

cout << "n :" << n << endl;
MPI_File_close(&f);

From my understanding this should read the first int "11" from the input.txt. But if gives me a very large number instead.

What am I doing wrong?

回答1:

MPI_File_Read reads a binary representation of an MPI_INT from your file. If you give it an ASCII (text-) -file it'll probably interpret the first 4 characters as one 32-bit integer and return a "very large number" just as you describe.

In that case, you could for example read the whole file into a buffer and then use sscanf() or any other text parsing function you have available.



回答2:

I think you can use similar API: MPI_File_write to generate the binary file you wanted easily.

char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_CREATE| MPI_MODE_RDWR, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
int data[10];
data[0]=11;
data[1]=3;data[2]=4;data[3]=5;data[4]=2;
MPI_File_write(f, data, 5, MPI_INT, &status);
MPI_File_close(&f);

After you run the above code using 1 process, you can get the binary file using MPI_File_read can read



标签: c++ mpi