【问题标题】:Writing to an output file in c MPI在 c MPI 中写入输出文件
【发布时间】:2014-04-12 21:15:02
【问题描述】:

我正在处理这个 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 输出到文件。如果有人对此问题有解决方案,将不胜感激。

【问题讨论】:

    标签: c file output mpi


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 2014-06-15
        • 2013-03-26
        相关资源
        最近更新 更多