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() + ".dat")));
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 + ".dat"));
141  if (is.good())
142  {
143  fName = fName + "_" + timeName;
144  }
145 
146  osPtr.reset(new OFstream(outputDir/(fName + ".dat")));
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 {}
203 
204 
206 (
207  const objectRegistry& obr,
208  const fileName& prefix,
209  const word& name,
210  const bool writeToFile
211 )
212 :
213  fileObr_(obr),
214  prefix_(prefix),
215  fileName_(name),
216  filePtr_(nullptr),
217  writePrecision_(IOstream::defaultPrecision()),
218  writeToFile_(writeToFile),
219  updateHeader_(true),
220  writtenHeader_(false),
221  useUserTime_(true),
222  startTime_(obr.time().startTime().value())
223 {}
224 
225 
227 (
228  const objectRegistry& obr,
229  const fileName& prefix,
230  const word& name,
231  const dictionary& dict,
232  const bool writeToFile
233 )
234 :
235  writeFile(obr, prefix, name, writeToFile)
236 {
237  read(dict);
238 
239  if (writeToFile_)
240  {
242  }
243 }
244 
245 
246 // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
247 
249 {
250  writePrecision_ =
251  dict.getCheckOrDefault
252  (
253  "writePrecision",
255  labelMinMax::ge(0)
256  );
257 
258  updateHeader_ = dict.getOrDefault("updateHeader", updateHeader_);
259 
260  // Only write on master
261  writeToFile_ =
262  Pstream::master() && dict.getOrDefault("writeToFile", writeToFile_);
263 
264  // Use user time, e.g. CA deg in preference to seconds
265  useUserTime_ = dict.getOrDefault("useUserTime", true);
266 
267  return true;
268 }
269 
270 
272 {
273  if (!writeToFile_)
274  {
275  return Snull;
276  }
277 
278  if (!filePtr_)
279  {
281  << "File pointer not allocated\n";
282  }
283 
284  return *filePtr_;
285 }
286 
289 {
290  return writeToFile_;
291 }
292 
295 {
296  return (Pstream::master() && writeToFile_ && filePtr_);
297 }
298 
301 {
302  return (Pstream::master() && writeToFile_ && !filePtr_);
303 }
304 
305 
307 {
308  return
309  Pstream::master() && writeToFile_ && (updateHeader_ || !writtenHeader_);
310 }
311 
312 
314 {
315  return writePrecision_ + addChars;
316 }
317 
318 
320 (
321  Ostream& os,
322  const string& str
323 ) const
324 {
325  os << setw(1) << "#";
326 
327  if (str.size())
328  {
329  os << setw(1) << ' '
330  << setf(ios_base::left) << setw(charWidth() - 2) << str.c_str();
331  }
332 }
333 
334 
336 (
337  Ostream& os,
338  const string& str
339 ) const
340 {
341  os << tab << setw(charWidth()) << str.c_str();
342 }
343 
344 
346 (
347  Ostream& os,
348  const string& str
349 ) const
350 {
351  writeCommented(os, str);
352  os << nl;
353 }
354 
355 
357 {
358  const scalar timeValue =
359  (
360  useUserTime_
361  ? fileObr_.time().timeOutputValue()
362  : fileObr_.time().value()
363  );
364 
365  os << setw(charWidth()) << Time::timeName(timeValue);
366 }
367 
368 
370 {
371  writeHeader(os, "===");
372 }
373 
374 
375 // ************************************************************************* //
virtual OFstream & file()
Return access to the file (if only 1)
Definition: writeFile.C:264
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:287
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:339
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
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition: error.H:598
virtual void writeBreak(Ostream &os) const
Write a break marker to the stream.
Definition: writeFile.C:362
virtual void resetFile(const word &name)
Reset internal file pointer to new file with new name.
Definition: writeFile.C:165
writeFile(const objectRegistry &obr, const fileName &prefix, const word &name="undefined", const bool writeToFile=true)
Construct from objectRegistry, prefix, fileName.
Definition: writeFile.C:199
Output to file stream, using an OSstream.
Definition: OFstream.H:49
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:423
static label addChars
Additional characters for writing.
Definition: writeFile.H:274
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
autoPtr< OFstream > filePtr_
File pointer.
Definition: writeFile.H:136
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:293
word timeName
Definition: getTimeIndex.H:3
virtual void writeCommented(Ostream &os, const string &str) const
Write a commented string to stream.
Definition: writeFile.C:313
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:299
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
Smanip< ios_base::fmtflags > setf(const ios_base::fmtflags flags)
Definition: IOmanip.H:169
virtual bool writeToFile() const
Flag to allow writing to file.
Definition: writeFile.C:281
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:306
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
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:241
virtual void writeCurrentTime(Ostream &os) const
Write the current time to stream.
Definition: writeFile.C:349
bool writeToFile_
Flag to enable/disable writing to file.
Definition: writeFile.H:146
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:627
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:1082
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
word fileName_
Name of file.
Definition: writeFile.H:131
Foam::label startTime
IOstream & scientific(IOstream &io)
Definition: IOstream.H:563
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:329