在c MPI中写入输出文件



我正在编写这段MPI代码,一切都很正常,但我在将程序输出写入文件时遇到了问题。这里有一些代码来说明我的问题

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 counternn",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 %sn", 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 %dnn", my_rank, count, peer_rank);
            MPI_Barrier(MPI_COMM_WORLD);
            fprintf(filename,"Process %d incremented the count (%d) and sent it to process %dn", 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;}

我希望将printf语句的输出写入文件,但代码只将最后while循环迭代中的最后一个printf输出到文件。如果有人能解决这个问题,我们将不胜感激。

您正在反复打开输出文件a-new进行写入。默认情况下,这将截断为0字节。

将文件打开的行移到循环上方(外部),将fclose行移到底部,也移到循环外部。

不要每次都打开文件。打开一次并通过CCD_ 2。这是你的问题。

最新更新