写入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 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;} 

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

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

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

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