1 static char help[] = "Demonstrates PetscFOpens() and PetscSynchronizedFGets().\n\n"; 2 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; 11 12 PetscFunctionBeginUser; 13 PetscCall(PetscInitialize(&argc, &argv, NULL, help)); 14 MPI_Comm comm = PETSC_COMM_WORLD; 15 PetscCallMPI(MPI_Comm_rank(comm, &rank)); 16 17 // -- Create the file 18 PetscCall(PetscFOpen(comm, filename, "w", &fp)); 19 PetscCall(PetscFPrintf(comm, fp, line1)); 20 PetscCall(PetscFPrintf(comm, fp, line2)); 21 PetscCall(PetscSynchronizedFPrintf(comm, fp, "rank: %d\n", rank)); // Print rankid in order 22 PetscCall(PetscSynchronizedFlush(comm, fp)); 23 PetscCall(PetscFClose(comm, fp)); 24 25 { // -- Read the file 26 char line[512] = {0}; 27 PetscBool line_check; 28 PetscMPIInt size; 29 PetscInt line_rank; 30 31 PetscCall(PetscFOpen(comm, filename, "r", &fp)); 32 PetscCall(PetscSynchronizedFGets(comm, fp, sizeof(line), line)); 33 PetscCall(PetscStrncmp(line, line1, sizeof(line1), &line_check)); 34 PetscCheck(line_check, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Line 1 not read correctly. Got '%s', expected '%s'", line, line1); 35 PetscCall(PetscSynchronizedFGets(comm, fp, sizeof(line), line)); 36 PetscCall(PetscStrncmp(line, line2, sizeof(line2), &line_check)); 37 PetscCheck(line_check, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Line 2 not read correctly. Got '%s', expected '%s'", line, line2); 38 PetscCallMPI(MPI_Comm_size(comm, &size)); 39 for (PetscInt i = 0; i < size; i++) { 40 PetscCall(PetscSynchronizedFGets(comm, fp, sizeof(line), line)); 41 sscanf(line, "rank: %" PetscInt_FMT, &line_rank); 42 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); 43 } 44 45 PetscCall(PetscFClose(comm, fp)); 46 } 47 48 PetscCall(PetscFinalize()); 49 return 0; 50 } 51 52 /*TEST 53 54 test: 55 nsize: 3 56 output_file: output/empty.out 57 58 TEST*/ 59