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