writeFile.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | www.openfoam.com
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8  Copyright (C) 2012-2018 OpenFOAM Foundation
9  Copyright (C) 2015-2022 OpenCFD Ltd.
10 -------------------------------------------------------------------------------
11 License
12  This file is part of OpenFOAM.
13 
14  OpenFOAM is free software: you can redistribute it and/or modify it
15  under the terms of the GNU General Public License as published by
16  the Free Software Foundation, either version 3 of the License, or
17  (at your option) any later version.
18 
19  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
20  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22  for more details.
23 
24  You should have received a copy of the GNU General Public License
25  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
26 
27 \*---------------------------------------------------------------------------*/
28 
29 #include "writeFile.H"
30 #include "Time.H"
31 #include "polyMesh.H"
32 #include "IFstream.H"
33 #include "functionObject.H"
34 
35 // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
36 
38 
39 
40 // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * //
41 
43 {
44  os.setf(ios_base::scientific, ios_base::floatfield);
45  os.precision(writePrecision_);
46  os.width(charWidth());
47 }
48 
49 
51 {
52  // Put in undecomposed case
53  // (Note: gives problems for distributed data running)
54 
55  fileName baseDir
56  (
57  fileObr_.time().globalPath()
59  );
60 
61  // Append mesh region name if not default region
62  const auto* meshPtr = isA<polyMesh>(fileObr_);
63  if (meshPtr)
64  {
65  baseDir /= meshPtr->regionName();
66  }
67  baseDir.clean(); // Remove unneeded ".."
68 
69  return baseDir;
70 }
71 
72 
74 {
75  return baseFileDir()/prefix_/fileObr_.time().timeName();
76 }
77 
78 
80 (
81  const fileName& fName
82 ) const
83 {
84  return baseFileDir()/prefix_/fName;
85 }
86 
87 
89 (
90  const fileName& fName
91 ) const
92 {
93  autoPtr<OFstream> osPtr;
94 
95  if (Pstream::master() && writeToFile_)
96  {
97  fileName outputDir(filePath(fName).path());
98 
99  mkDir(outputDir);
100 
101  osPtr.reset(new OFstream(outputDir/(fName.name() + ext_)));
102 
103  if (!osPtr->good())
104  {
105  FatalIOErrorInFunction(osPtr()) << "Cannot open file"
106  << exit(FatalIOError);
107  }
108 
109  initStream(osPtr());
110  }
111 
112  return osPtr;
113 }
114 
115 
117 (
118  const word& name,
119  scalar timeValue
120 ) const
121 {
122  autoPtr<OFstream> osPtr;
123 
124  if (Pstream::master() && writeToFile_)
125  {
126  if (useUserTime_)
127  {
128  timeValue = fileObr_.time().timeToUserTime(timeValue);
129  }
130 
131  const word timeName = Time::timeName(timeValue);
132 
133  fileName outputDir(baseFileDir()/prefix_/timeName);
134 
135  mkDir(outputDir);
136 
137  word fName(name);
138 
139  // Check if file already exists
140  IFstream is(outputDir/(fName + ext_));
141  if (is.good())
142  {
143  fName = fName + "_" + timeName;
144  }
145 
146  osPtr.reset(new OFstream(outputDir/(fName + ext_)));
147 
148  if (!osPtr->good())
149  {
150  FatalIOErrorInFunction(osPtr()) << "Cannot open file"
151  << exit(FatalIOError);
152  }
153 
154  initStream(osPtr());
155  }
157  return osPtr;
158 }
159 
160 
163 (
164  const word& name
165 ) const
166 {
167  return newFileAtTime(name, startTime_);
168 
169 }
170 
171 
173 {
174  fileName_ = fileName;
175  filePtr_ = newFileAtStartTime(fileName_);
176 }
177 
178 
180 (
181  const label offset
182 ) const
183 {
184  return setw(writePrecision_ + addChars + offset);
185 }
186 
187 
188 // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
189 
191 :
192  fileObr_(wf.fileObr_),
193  prefix_(wf.prefix_),
194  fileName_(wf.fileName_),
195  filePtr_(nullptr),
196  writePrecision_(wf.writePrecision_),
197  writeToFile_(wf.writeToFile_),
198  updateHeader_(wf.updateHeader_),
199  writtenHeader_(wf.writtenHeader_),
200  useUserTime_(wf.useUserTime_),
201  startTime_(wf.startTime_),
202  ext_(wf.ext_)
203 {}
204 
205 
207 (
208  const objectRegistry& obr,
209  const fileName& prefix,
210  const word& name,
211  const bool writeToFile,
212  const string& ext
213 )
214 :
215  fileObr_(obr),
216  prefix_(prefix),
217  fileName_(name),
218  filePtr_(nullptr),
219  writePrecision_(IOstream::defaultPrecision()),
220  writeToFile_(writeToFile),
221  updateHeader_(true),
222  writtenHeader_(false),
223  useUserTime_(true),
224  startTime_(obr.time().startTime().value()),
225  ext_(ext)
226 {}
227 
228 
230 (
231  const objectRegistry& obr,
232  const fileName& prefix,
233  const word& name,
234  const dictionary& dict,
235  const bool writeToFile,
236  const string& ext
237 )
238 :
239  writeFile(obr, prefix, name, writeToFile, ext)
240 {
241  read(dict);
242 }
243 
244 
245 // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
246 
248 {
249  writePrecision_ =
250  dict.getCheckOrDefault
251  (
252  "writePrecision",
254  labelMinMax::ge(0)
255  );
256 
257  updateHeader_ = dict.getOrDefault("updateHeader", updateHeader_);
258 
259  // Only write on master
260  writeToFile_ =
261  Pstream::master() && dict.getOrDefault("writeToFile", writeToFile_);
262 
263  // Use user time, e.g. CA deg in preference to seconds
264  useUserTime_ = dict.getOrDefault("useUserTime", true);
265 
266  return true;
267 }
268 
269 
271 {
272  ext_ = ext;
273  return ext_;
274 }
275 
276 
278 {
279  if (!writeToFile_)
280  {
281  return Snull;
282  }
283 
284  if (!filePtr_ && writeToFile_)
285  {
286  filePtr_ = newFileAtStartTime(fileName_);
287  }
288 
289  return *filePtr_;
290 }
291 
294 {
295  return writeToFile_;
296 }
297 
300 {
301  return (Pstream::master() && writeToFile_ && filePtr_);
302 }
303 
306 {
307  return (Pstream::master() && writeToFile_ && !filePtr_);
308 }
309 
310 
312 {
313  return
314  Pstream::master() && writeToFile_ && (updateHeader_ || !writtenHeader_);
315 }
316 
317 
319 {
320  return writePrecision_ + addChars;
321 }
322 
323 
325 (
326  Ostream& os,
327  const string& str
328 ) const
329 {
330  os << setw(1) << "#";
331 
332  if (str.size())
333  {
334  os << setw(1) << ' '
335  << setf(ios_base::left) << setw(charWidth() - 2) << str.c_str();
336  }
337 }
338 
339 
341 (
342  Ostream& os,
343  const string& str
344 ) const
345 {
346  os << tab << setw(charWidth()) << str.c_str();
347 }
348 
349 
351 (
352  Ostream& os,
353  const string& str
354 ) const
355 {
356  writeCommented(os, str);
357  os << nl;
358 }
359 
360 
362 {
363  const scalar timeValue =
364  (
365  useUserTime_
366  ? fileObr_.time().timeOutputValue()
367  : fileObr_.time().value()
368  );
369 
370  os << setw(charWidth()) << Time::timeName(timeValue);
371 }
372 
373 
375 {
376  writeHeader(os, "===");
377 }
378 
379 
380 // ************************************************************************* //
virtual OFstream & file()
Return access to the file (if only 1)
Definition: writeFile.C:270
dictionary dict
A class for handling file names.
Definition: fileName.H:72
virtual bool canWriteToFile() const
Flag to allow writing to the file.
Definition: writeFile.C:292
static void writeHeader(Ostream &os, const word &fieldName)
virtual void writeHeader(Ostream &os, const string &str) const
Write a commented header to stream.
Definition: writeFile.C:344
writeFile(const objectRegistry &obr, const fileName &prefix, const word &name="undefined", const bool writeToFile=true, const string &ext=".dat")
Construct from objectRegistry, prefix, fileName.
Definition: writeFile.C:200
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:125
A list of keyword definitions, which are a keyword followed by a number of values (eg...
Definition: dictionary.H:129
virtual void writeBreak(Ostream &os) const
Write a break marker to the stream.
Definition: writeFile.C:367
virtual void resetFile(const word &name)
Reset internal file pointer to new file with new name.
Definition: writeFile.C:165
Output to file stream as an OSstream, normally using std::ofstream for the actual output...
Definition: OFstream.H:71
constexpr char nl
The newline &#39;\n&#39; character (0x0a)
Definition: Ostream.H:50
OFstream Snull
Global predefined null output stream "/dev/null".
static unsigned int defaultPrecision() noexcept
Return the default precision.
Definition: IOstream.H:418
static label addChars
Additional characters for writing.
Definition: writeFile.H:279
constexpr char tab
The tab &#39;\t&#39; character(0x09)
Definition: Ostream.H:49
virtual autoPtr< OFstream > newFile(const fileName &fName) const
Return autoPtr to a new file using file name.
Definition: writeFile.C:82
const word & timeName() const noexcept
Return the current time name.
Definition: TimeStateI.H:30
virtual const string & setExt(const string &ext)
Set extension.
Definition: writeFile.C:263
bool read(const char *buf, int32_t &val)
Same as readInt32.
Definition: int32.H:127
void reset(T *p=nullptr) noexcept
Delete managed object and set to new given pointer.
Definition: autoPtrI.H:37
fileName filePath(const fileName &fName) const
Return the full path for the supplied file name.
Definition: writeFile.C:73
virtual bool canResetFile() const
Flag to allow resetting the file.
Definition: writeFile.C:298
word timeName
Definition: getTimeIndex.H:3
virtual void writeCommented(Ostream &os, const string &str) const
Write a commented string to stream.
Definition: writeFile.C:318
bool mkDir(const fileName &pathName, mode_t mode=0777)
Make a directory and return an error if it could not be created.
Definition: POSIX.C:614
word name(const expressions::valueTypeCode typeCode)
A word representation of a valueTypeCode. Empty for expressions::valueTypeCode::INVALID.
Definition: exprTraits.C:127
bool good() const noexcept
True if the managed pointer is non-null.
Definition: autoPtr.H:206
virtual bool canWriteHeader() const
Flag to allow writing the header.
Definition: writeFile.C:304
void initStream(Ostream &os) const
Initialise the output stream for writing.
Definition: writeFile.C:35
Foam::autoPtr< Foam::dynamicFvMesh > meshPtr
A class for handling words, derived from Foam::string.
Definition: word.H:63
static MinMax< T > ge(const T &minVal)
A semi-infinite range from minVal to the type max.
Definition: MinMaxI.H:24
virtual bool writeToFile() const
Flag to allow writing to file.
Definition: writeFile.C:286
fileName baseTimeDir() const
Return the base directory for the current time value.
Definition: writeFile.C:66
virtual autoPtr< OFstream > newFileAtTime(const word &name, scalar timeValue) const
Return autoPtr to a new file for a given time.
Definition: writeFile.C:110
virtual label charWidth() const
Return width of character stream output.
Definition: writeFile.C:311
label writePrecision_
Write precision.
Definition: writeFile.H:141
An Ostream is an abstract base class for all output systems (streams, files, token lists...
Definition: Ostream.H:56
Smanip< std::ios_base::fmtflags > setf(std::ios_base::fmtflags flags)
Definition: IOmanip.H:169
static std::string name(const std::string &str)
Return basename (part beyond last /), including its extension.
Definition: fileNameI.H:192
OBJstream os(runTime.globalPath()/outputName)
fileName path(UMean.rootPath()/UMean.caseName()/"graphs"/UMean.instance())
virtual autoPtr< OFstream > newFileAtStartTime(const word &name) const
Return autoPtr to a new file using the simulation start time.
Definition: writeFile.C:156
virtual bool read(const dictionary &dict)
Read.
Definition: writeFile.C:240
virtual void writeCurrentTime(Ostream &os) const
Write the current time to stream.
Definition: writeFile.C:354
fileName baseFileDir() const
Return the base directory for output.
Definition: writeFile.C:43
An IOstream is an abstract base class for all input/output systems; be they streams, files, token lists etc.
Definition: IOstream.H:82
#define FatalIOErrorInFunction(ios)
Report an error message using Foam::FatalIOError.
Definition: error.H:637
Omanip< int > valueWidth(const label offset=0) const
Return the value width when writing to stream with optional offset.
Definition: writeFile.C:173
static bool master(const label communicator=worldComm)
True if process corresponds to the master rank in the communicator.
Definition: UPstream.H:1094
static word outputPrefix
Directory prefix.
Omanip< int > setw(const int i)
Definition: IOmanip.H:199
Registry of regIOobjects.
Base class for writing single files from the function objects.
Definition: writeFile.H:112
Foam::label startTime
A class for handling character strings derived from std::string.
Definition: string.H:72
IOstream & scientific(IOstream &io)
Definition: IOstream.H:578
An Ostream manipulator taking arguments.
Definition: IOmanip.H:44
IOerror FatalIOError
Error stream (stdout output on all processes), with additional &#39;FOAM FATAL IO ERROR&#39; header text and ...
virtual void writeTabbed(Ostream &os, const string &str) const
Write a tabbed string to stream.
Definition: writeFile.C:334