]> git.treefish.org Git - phys/latlib.git/blob - writeout.cpp
eb14309e53c93959e53e4dc4668336af9681c339
[phys/latlib.git] / writeout.cpp
1 #include "writeout.h"
2
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <iostream>
8 #include <time.h>
9 #include <sstream>
10 #include <dirent.h>
11 #include <errno.h>
12
13 using namespace std;
14
15 string writeout::tstamp()
16 {
17     stringstream sstr;
18     sstr << time (NULL);
19     return sstr.str();
20 }
21
22 writeout::writeout(const string& wdir, const string& signature, 
23                    const int& rank, const int& procs)
24 {
25   if(wdir != ""){
26     numprocs = procs;
27     sprintf(cRank, "%d", rank);
28     fulldir = wdir + "/" + tstamp() + "_" + signature;
29     mkdir( fulldir.c_str(),  0775);
30
31     if(rank>0) of.open( (fulldir + "/rank" + cRank + ".tmp").c_str() );
32     else of.open( (fulldir + "/" + signature + ".dat").c_str() );
33
34     buf = of.rdbuf();
35   }
36   else{
37     buf = cout.rdbuf();
38   }
39   out = new ostream(buf);
40 }
41
42 writeout::~writeout()
43 {
44   if(fulldir != "")
45     {
46       if( cRank[0] == '0' )
47         {
48           int jobsdone=0;
49           while(jobsdone<numprocs-1)
50             {
51               string nextfile;
52               if( (nextfile=getdatfile()) == "" ) sleep(1);
53               else
54                 {
55                   cerr << "collecting " << nextfile << endl;
56
57                   ifstream myfile( (fulldir + "/" + nextfile).c_str() );
58                   while(true){
59                     string line;
60                     getline(myfile, line);
61                     if( !myfile.good() ) break;
62                     of << line << endl << flush;
63                   }
64                   myfile.close();
65                   remove( (fulldir + "/" + nextfile).c_str() );
66                   jobsdone++;
67                 }
68             }
69           of << "#end" << endl << flush;
70           of.close();
71         }
72       else
73         {
74           of.close();
75           rename((fulldir + "/rank" + cRank + ".tmp").c_str(),
76                  (fulldir + "/rank" + cRank + ".part").c_str());
77         }
78     }
79 }
80
81 string writeout::getdatfile()
82 {
83   string myfile;
84   DIR *dp;
85   struct dirent *dirp;
86
87   if((dp  = opendir(fulldir.c_str())) == NULL) {
88     cerr << "Error(" << errno << ") opening " << fulldir << endl;
89     return "";
90   }
91   
92   while ((dirp = readdir(dp)) != NULL)
93     {
94       myfile = string(dirp->d_name);
95       if(myfile.length() > 3 && myfile.substr(myfile.length()-4) == "part")
96         return myfile;
97     }
98
99   return "";
100 }