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