Writing to an output file in c MPI

2019-08-15 19:35发布

问题:

I am working on this MPI code and everything is almost working as it should, but I am having trouble writing the output of the program to a file. Here is some code to illustrate my problem

int main(int argc, char *argv[]){
FILE *filename;
int size, my_rank;
int count =0;
int tag =99;

int limit = 5;
MPI_Init(&argc, &argv);
MPI_Status status;
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);

if(my_rank ==0)
    printf("Process %d started the game and initialized the counter\n\n",my_rank);
MPI_Barrier(MPI_COMM_WORLD);

if (size != 2) {//abort if the number of processes is not 2.
        fprintf(stderr, "only 2 processes shall be used for %s\n", argv[0]);
        MPI_Abort(MPI_COMM_WORLD, 1); 
    }   
 int peer_rank = (my_rank + 1) % 2;
    while(count < limit){
        filename = fopen("ping_pong_output.txt", "w");
        if(my_rank == count % 2){
            count++;
            MPI_Send(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD);
            printf("Process %d incremented the count (%d) and sent it to process %d\n\n", my_rank, count, peer_rank);
            MPI_Barrier(MPI_COMM_WORLD);
            fprintf(filename,"Process %d incremented the count (%d) and sent it to process %d\n", my_rank, count, peer_rank);
        } else{
             MPI_Barrier(MPI_COMM_WORLD);
            MPI_Recv(&count, 1, MPI_INT, peer_rank, tag, MPI_COMM_WORLD,
           &status);
             MPI_Barrier(MPI_COMM_WORLD);
           printf("Process %d received the count from process %d.\n", my_rank, peer_rank);
           fprintf(filename,"Process %d received the count.\n", peer_rank);
           }
      fclose(filename);
  }
  MPI_Finalize();
  return 0;}

I want the output of the printf statements written to a file, but the code is only outputting the last printf in the final while loop iteration to the file. If anybody has a solution to this problem it would be greatly appreciated.

回答1:

You are repeatedly opening your output file a-new for writing. By default, that will truncate it to 0 bytes.

Move the file open line above (outside) your loop, and the fclose line to the bottom, also outside the loop.



回答2:

Do not open your file every time. open it once and pass FILE-POINTER. This is your problem.



标签: c file output mpi