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.