]> git.treefish.org Git - phys/latlib.git/blob - writeout.cpp
wrote neigh test routine
[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 + ".tmp";
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           rename( fulldir.c_str(), fulldir.substr(0, fulldir.length()-4).c_str() );
73         }
74       else
75         {
76           of.close();
77           rename((fulldir + "/rank" + cRank + ".tmp").c_str(),
78                  (fulldir + "/rank" + cRank + ".part").c_str());
79         }
80     }
81 }
82
83 string writeout::getdatfile()
84 {
85   string myfile;
86   DIR *dp;
87   struct dirent *dirp;
88
89   if((dp  = opendir(fulldir.c_str())) == NULL) {
90     cerr << "Error(" << errno << ") opening " << fulldir << endl;
91     return "";
92   }
93   
94   while ((dirp = readdir(dp)) != NULL)
95     {
96       myfile = string(dirp->d_name);
97       if(myfile.length() > 3 && myfile.substr(myfile.length()-4) == "part")
98         return myfile;
99     }
100
101   return "";
102 }