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, (char *)0, help));
14: MPI_Comm comm = PETSC_COMM_WORLD;
15: PetscCallMPI(MPI_Comm_rank(comm, &rank));
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));
25: { // -- Read the file
26: char line[512] = {0};
27: PetscBool line_check;
28: PetscMPIInt size;
29: PetscInt line_rank;
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: }
45: PetscCall(PetscFClose(comm, fp));
46: }
48: PetscCall(PetscFinalize());
49: return 0;
50: }
52: /*TEST
54: test:
55: nsize: 3
57: TEST*/