using mpi_2上看到的,顺便敲下代码
#include "mpi.h"
#include<stdio.h>
#define BUFSIZE 100
int main(int argc,char *argv[]){
int i,myrank,buf[BUFSIZE];
char filename[128];
FILE *myfile;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
for(int i=0;i<BUFSIZE;i++)
buf[i]=myrank*BUFSIZE+i;
sprintf(filename,"testfile.%d",myrank);
myfile=fopen(filename,"w");
fwrite(buf,sizeof(int),BUFSIZE,myfile);
fclose(myfile);
MPI_Finalize();
return 0;
}
#include "mpi.h"
#include<stdio.h>
#define BUFSIZE 100
int main(int argc,char *argv[]){
int i,myrank,buf[BUFSIZE];
char filename[128];
MPI_File myfile;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
for(int i=0;i<BUFSIZE;i++)
buf[i]=myrank*BUFSIZE+i;
sprintf(filename,"testfile.%d",myrank);
MPI_File_open(MPI_COMM_SELF,filename,
MPI_MODE_WRONLY|MPI_MODE_CREATE,
MPI_INFO_NULL,&myfile);
MPI_File_write(myfile,buf,BUFSIZE,MPI_INT,
MPI_STATUS_IGNORE);
MPI_File_close(&myfile);
MPI_Finalize();
return 0;
}
需要注意的是MPI_File_read_at读取的是二进制文件,如果不是二进制写的比如ASCII编码的文本文件,读出来的数据便不正确
#include<stdio.h>
#include "mpi.h"
int main(int argc,char *argv[]){
int rank,np;
int buf[4];
MPI_File file_handle;
char *fname="2.dat";
MPI_Status sta;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&np);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_File_open(MPI_COMM_WORLD,fname,MPI_MODE_RDONLY,MPI_INFO_NULL,&file_handle);
MPI_File_read_at(file_handle,0,buf,2,MPI_INT,&sta);
printf("%d %d\n",buf[0],buf[1]);
MPI_File_close(&file_handle);
MPI_Finalize();
return 0;
}