Actual source code: ex17.c

  1: static char help[] = "Demonstrates PetscFOpens() and PetscSynchronizedFGets().\n\n";

  3: #include <petscsys.h>
  4: int main(int argc, char **argv)
  5: {
  6:   const char  line1[]    = "hello 1\n";
  7:   const char  line2[]    = "hello 2\n";
  8:   const char  filename[] = "testfile";
  9:   PetscMPIInt rank;
 10:   FILE       *fp;

 12:   PetscFunctionBeginUser;
 13:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
 14:   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));

 16:   // -- Create the file
 17:   PetscCall(PetscFOpen(PETSC_COMM_WORLD, filename, "w", &fp));
 18:   PetscCall(PetscFPrintf(PETSC_COMM_WORLD, fp, line1));
 19:   PetscCall(PetscFPrintf(PETSC_COMM_WORLD, fp, line2));
 20:   PetscCall(PetscSynchronizedFPrintf(PETSC_COMM_WORLD, fp, "rank: %d\n", rank)); // Print rankid in order
 21:   PetscCall(PetscSynchronizedFlush(PETSC_COMM_WORLD, fp));
 22:   PetscCall(PetscFClose(PETSC_COMM_WORLD, fp));

 24:   { // -- Read the file
 25:     char        line[512] = {0};
 26:     PetscBool   line_check;
 27:     PetscMPIInt size;
 28:     PetscInt    line_rank;

 30:     PetscCall(PetscFOpen(PETSC_COMM_WORLD, filename, "r", &fp));
 31:     PetscCall(PetscSynchronizedFGets(PETSC_COMM_WORLD, fp, sizeof(line), line));
 32:     PetscCall(PetscStrncmp(line, line1, sizeof(line1), &line_check));
 33:     PetscCheck(line_check, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Line 1 not read correctly. Got '%s', expected '%s'", line, line1);
 34:     PetscCall(PetscSynchronizedFGets(PETSC_COMM_WORLD, fp, sizeof(line), line));
 35:     PetscCall(PetscStrncmp(line, line2, sizeof(line2), &line_check));
 36:     PetscCheck(line_check, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Line 2 not read correctly. Got '%s', expected '%s'", line, line2);
 37:     PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
 38:     for (PetscInt i = 0; i < size; i++) {
 39:       PetscCall(PetscSynchronizedFGets(PETSC_COMM_WORLD, fp, sizeof(line), line));
 40:       sscanf(line, "rank: %" PetscInt_FMT, &line_rank);
 41:       PetscCheck(i == line_rank, PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED, "Did not find correct rank line in file. Expected %" PetscInt_FMT ", found %" PetscInt_FMT, i, line_rank);
 42:     }

 44:     PetscCall(PetscFClose(PETSC_COMM_WORLD, fp));
 45:   }

 47:   PetscCall(PetscFinalize());
 48:   return 0;
 49: }

 51: /*TEST

 53:    test:
 54:     nsize: 3
 55:     output_file: output/empty.out

 57: TEST*/