2014-04-12 82 views
1

我正在處理這個MPI代碼,所有東西幾乎都是按照它應該的方式工作的,但是我無法將程序的輸出寫入文件。下面是一些代碼來說明我的問題在c 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。如果有人有解決這個問題,將不勝感激。

回答

0

你反覆打開你的輸出文件a-new進行寫作。默認情況下,將截取爲它爲0字節。

將文件打開行移至循環的上方(外部),並將fclose行移至循環的底部。

0

不要每次打開文件。打開一次並通過FILE-POINTER。這是你的問題。