Remove gmx::File (except for File::exists())
authorTeemu Murtola <teemu.murtola@gmail.com>
Fri, 26 Jun 2015 04:16:48 +0000 (07:16 +0300)
committerTeemu Murtola <teemu.murtola@gmail.com>
Sat, 4 Jul 2015 13:00:02 +0000 (15:00 +0200)
Move remaining static methods to either path.h, or to the file stream
classes.

Change-Id: I53e910051b9ef57e501adad4cec1a4b5295d24a7

23 files changed:
src/gromacs/commandline/cmdlineprogramcontext.cpp
src/gromacs/commandline/tests/cmdlinehelpmodule.cpp
src/gromacs/commandline/tests/pargs.cpp
src/gromacs/gmxpreprocess/fflibutil.cpp
src/gromacs/gmxpreprocess/pdb2top.cpp
src/gromacs/onlinehelp/helpformat.h
src/gromacs/utility/CMakeLists.txt
src/gromacs/utility/datafilefinder.cpp
src/gromacs/utility/file.cpp [deleted file]
src/gromacs/utility/file.h [deleted file]
src/gromacs/utility/fileredirector.cpp
src/gromacs/utility/filestream.cpp
src/gromacs/utility/filestream.h
src/gromacs/utility/path.cpp
src/gromacs/utility/path.h
src/gromacs/utility/textreader.cpp
src/gromacs/utility/textreader.h
src/gromacs/utility/textwriter.cpp
src/gromacs/utility/textwriter.h
src/programs/mdrun/tests/moduletest.cpp
src/testutils/cmdlinetest.cpp
src/testutils/integrationtests.cpp
src/testutils/stringtest.cpp

index 5d98a4ae5166157bc29e6c54046e06ac6405d461..84204246873d172544060c5df7002ac111816541 100644 (file)
@@ -60,7 +60,6 @@
 
 #include "buildinfo.h"
 #include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/gmxassert.h"
 #include "gromacs/utility/path.h"
 #include "gromacs/utility/stringutil.h"
index 7be3fb5ed7e738c8b02d5605beeaca477390a70d..5fada52c35de53dd3fec1d0fd73e1095e89bb9fe 100644 (file)
@@ -48,7 +48,7 @@
 #include "gromacs/commandline/cmdlinemodulemanager.h"
 #include "gromacs/options/basicoptions.h"
 #include "gromacs/options/options.h"
-#include "gromacs/utility/file.h"
+#include "gromacs/utility/textwriter.h"
 
 #include "gromacs/onlinehelp/tests/mock_helptopic.h"
 #include "testutils/cmdlinetest.h"
@@ -123,7 +123,7 @@ TEST_F(CommandLineHelpModuleTest, ExportsHelp)
         "test", "help", "-export", "rst"
     };
     // TODO: Find a more elegant solution, or get rid of the links.dat altogether.
-    gmx::File::writeFileFromString("links.dat", "");
+    gmx::TextWriter::writeFileFromString("links.dat", "");
     CommandLine        args(cmdline);
     initManager(args, "test");
     MockOptionsModule &mod1 = addOptionsModule("module", "First module");
index d74f12f9877b437e37aa97e6dc8a13f98449ba0d..53ea895be10a4677c24204753d5ce2837f869932 100644 (file)
@@ -51,9 +51,9 @@
 #include <gtest/gtest.h>
 
 #include "gromacs/utility/arrayref.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/path.h"
 #include "gromacs/utility/stringutil.h"
+#include "gromacs/utility/textwriter.h"
 
 #include "testutils/cmdlinetest.h"
 #include "testutils/testasserts.h"
@@ -108,7 +108,7 @@ class ParseCommonArgsTest : public ::testing::Test
                                FileArgumentType type)
         {
             std::string filename(tempFiles_.getTemporaryFilePath(extension));
-            gmx::File::writeFileFromString(filename, "Dummy file");
+            gmx::TextWriter::writeFileFromString(filename, "Dummy file");
             if (name != NULL)
             {
                 args_.append(name);
index f986f5e545afac46530ad7042743a2ed528bbdbc..11e1f5ae8479677c603445a69a469efc61a77555 100644 (file)
@@ -47,7 +47,6 @@
 #include "gromacs/utility/directoryenumerator.h"
 #include "gromacs/utility/exceptions.h"
 #include "gromacs/utility/fatalerror.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/futil.h"
 #include "gromacs/utility/path.h"
 #include "gromacs/utility/smalloc.h"
index 920c3a38f9db69948ce9a2ff4d7dc53ef8800c4a..49b7316358b22428befbfc097570f5610bdb3508 100644 (file)
@@ -70,7 +70,6 @@
 #include "gromacs/utility/dir_separator.h"
 #include "gromacs/utility/exceptions.h"
 #include "gromacs/utility/fatalerror.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/futil.h"
 #include "gromacs/utility/path.h"
 #include "gromacs/utility/programcontext.h"
index 99e16425b5639626944d081b034be8413d745ffb..bf99fdd7c4771a4435fa3aecdd4c1bdbb2705302 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
+ * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
  * and including many others, as listed in the AUTHORS file in the
  * top-level source directory and at http://www.gromacs.org.
@@ -50,7 +50,6 @@
 namespace gmx
 {
 
-class File;
 class HelpWriterContext;
 
 /*! \libinternal \brief
index 1933e660a6ce406932b430e016d7cb4439e5d129..1ce2ce4b20fd1ea87e347a8b6dbe4823279b16d9 100644 (file)
@@ -44,7 +44,6 @@ gmx_install_headers(
     errorcodes.h
     exceptions.h
     fatalerror.h
-    file.h
     flags.h
     futil.h
     gmxassert.h
index 2bc6a9b875015052bd5bfca2fec774ca94c33a37..e773fff84b2a55db6f2c69199d288f9e43088ab0 100644 (file)
@@ -51,7 +51,7 @@
 #include "buildinfo.h"
 #include "gromacs/utility/directoryenumerator.h"
 #include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/file.h"
+#include "gromacs/utility/filestream.h"
 #include "gromacs/utility/path.h"
 #include "gromacs/utility/programcontext.h"
 #include "gromacs/utility/stringutil.h"
@@ -133,7 +133,7 @@ FILE *DataFileFinder::openFile(const DataFileOptions &options) const
         fprintf(debug, "Opening library file %s\n", fn);
     }
 #endif
-    return File::openRawHandle(filename, "r");
+    return TextInputFile::openRawHandle(filename);
 }
 
 std::string DataFileFinder::findFile(const DataFileOptions &options) const
diff --git a/src/gromacs/utility/file.cpp b/src/gromacs/utility/file.cpp
deleted file mode 100644 (file)
index b5415a1..0000000
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * This file is part of the GROMACS molecular simulation package.
- *
- * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
- * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
- * and including many others, as listed in the AUTHORS file in the
- * top-level source directory and at http://www.gromacs.org.
- *
- * GROMACS is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1
- * of the License, or (at your option) any later version.
- *
- * GROMACS is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with GROMACS; if not, see
- * http://www.gnu.org/licenses, or write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
- *
- * If you want to redistribute modifications to GROMACS, please
- * consider that scientific software is very special. Version
- * control is crucial - bugs must be traceable. We will be happy to
- * consider code for inclusion in the official distribution, but
- * derived work must not be called official GROMACS. Details are found
- * in the README & COPYING files - if they are missing, get the
- * official version at http://www.gromacs.org.
- *
- * To help us fund GROMACS development, we humbly ask that you cite
- * the research papers on the package. Check out http://www.gromacs.org.
- */
-/*! \internal \file
- * \brief
- * Implements gmx::File.
- *
- * \author Teemu Murtola <teemu.murtola@gmail.com>
- * \ingroup module_utility
- */
-#include "gmxpre.h"
-
-#include "file.h"
-
-#include "config.h"
-
-#include <cerrno>
-#include <cstdio>
-#include <cstring>
-
-#include <algorithm>
-#include <string>
-#include <vector>
-
-#include <sys/stat.h>
-
-#include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/gmxassert.h"
-#include "gromacs/utility/stringutil.h"
-
-namespace gmx
-{
-
-/*! \internal \brief
- * Private implementation class for File.
- *
- * \ingroup module_utility
- */
-class File::Impl
-{
-    public:
-        /*! \brief
-         * Initialize a file object with the given handle.
-         *
-         * \param[in]  fp     %File handle to use (may be NULL).
-         * \param[in]  bClose Whether this object should close its file handle.
-         */
-        Impl(FILE *fp, bool bClose);
-        ~Impl();
-
-        //! File handle for this object (may be NULL).
-        FILE                   *fp_;
-        /*! \brief
-         * Whether \p fp_ should be closed by this object.
-         *
-         * Can be true if \p fp_ is NULL.
-         */
-        bool                    bClose_;
-};
-
-File::Impl::Impl(FILE *fp, bool bClose)
-    : fp_(fp), bClose_(bClose)
-{
-}
-
-File::Impl::~Impl()
-{
-    if (fp_ != NULL && bClose_)
-    {
-        if (fclose(fp_) != 0)
-        {
-            // TODO: Log the error somewhere
-        }
-    }
-}
-
-// static
-FILE *File::openRawHandle(const char *filename, const char *mode)
-{
-    FILE *fp = fopen(filename, mode);
-    if (fp == NULL)
-    {
-        GMX_THROW_WITH_ERRNO(
-                FileIOError(formatString("Could not open file '%s'", filename)),
-                "fopen", errno);
-    }
-    return fp;
-}
-
-// static
-FILE *File::openRawHandle(const std::string &filename, const char *mode)
-{
-    return openRawHandle(filename.c_str(), mode);
-}
-
-File::File(const char *filename, const char *mode)
-    : impl_(new Impl(NULL, true))
-{
-    open(filename, mode);
-}
-
-File::File(const std::string &filename, const char *mode)
-    : impl_(new Impl(NULL, true))
-{
-    open(filename, mode);
-}
-
-File::~File()
-{
-}
-
-void File::open(const char *filename, const char *mode)
-{
-    GMX_RELEASE_ASSERT(impl_->fp_ == NULL,
-                       "Attempted to open the same file object twice");
-    // TODO: Port all necessary functionality from gmx_ffopen() here.
-    impl_->fp_ = openRawHandle(filename, mode);
-}
-
-void File::open(const std::string &filename, const char *mode)
-{
-    open(filename.c_str(), mode);
-}
-
-void File::close()
-{
-    GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
-                       "Attempted to close a file object that is not open");
-    GMX_RELEASE_ASSERT(impl_->bClose_,
-                       "Attempted to close a file object that should not be");
-    bool bOk = (fclose(impl_->fp_) == 0);
-    impl_->fp_ = NULL;
-    if (!bOk)
-    {
-        GMX_THROW_WITH_ERRNO(
-                FileIOError("Error while closing file"), "fclose", errno);
-    }
-}
-
-FILE *File::handle()
-{
-    GMX_RELEASE_ASSERT(impl_->fp_ != NULL,
-                       "Attempted to access a file object that is not open");
-    return impl_->fp_;
-}
-
-void File::readBytes(void *buffer, size_t bytes)
-{
-    errno = 0;
-    FILE  *fp = handle();
-    // TODO: Retry based on errno or something else?
-    size_t bytesRead = std::fread(buffer, 1, bytes, fp);
-    if (bytesRead != bytes)
-    {
-        if (feof(fp))
-        {
-            GMX_THROW(FileIOError(
-                              formatString("Premature end of file\n"
-                                           "Attempted to read: %d bytes\n"
-                                           "Successfully read: %d bytes",
-                                           static_cast<int>(bytes),
-                                           static_cast<int>(bytesRead))));
-        }
-        else
-        {
-            GMX_THROW_WITH_ERRNO(FileIOError("Error while reading file"),
-                                 "fread", errno);
-        }
-    }
-}
-
-void File::writeString(const char *str)
-{
-    if (fprintf(handle(), "%s", str) < 0)
-    {
-        GMX_THROW_WITH_ERRNO(FileIOError("Writing to file failed"),
-                             "fprintf", errno);
-    }
-}
-
-// static
-bool File::exists(const char *filename)
-{
-    if (filename == NULL)
-    {
-        return false;
-    }
-    FILE *test = fopen(filename, "r");
-    if (test == NULL)
-    {
-        return false;
-    }
-    else
-    {
-        fclose(test);
-        // Windows doesn't allow fopen of directory, so we don't need to check
-        // this separately.
-#ifndef GMX_NATIVE_WINDOWS
-        struct stat st_buf;
-        int         status = stat(filename, &st_buf);
-        if (status != 0 || !S_ISREG(st_buf.st_mode))
-        {
-            return false;
-        }
-#endif
-        return true;
-    }
-}
-
-// static
-bool File::exists(const std::string &filename)
-{
-    return exists(filename.c_str());
-}
-
-// static
-std::string File::readToString(const char *filename)
-{
-    // Binary mode is required on Windows to be able to determine a size
-    // that can be passed to fread().
-    File  file(filename, "rb");
-    FILE *fp = file.handle();
-
-    if (std::fseek(fp, 0L, SEEK_END) != 0)
-    {
-        GMX_THROW_WITH_ERRNO(FileIOError("Seeking to end of file failed"),
-                             "fseek", errno);
-    }
-    long len = std::ftell(fp);
-    if (len == -1)
-    {
-        GMX_THROW_WITH_ERRNO(FileIOError("Reading file length failed"),
-                             "ftell", errno);
-    }
-    if (std::fseek(fp, 0L, SEEK_SET) != 0)
-    {
-        GMX_THROW_WITH_ERRNO(FileIOError("Seeking to start of file failed"),
-                             "fseek", errno);
-    }
-
-    std::vector<char> data(len);
-    file.readBytes(&data[0], len);
-    file.close();
-
-    std::string result(&data[0], len);
-    // The below is necessary on Windows to make newlines stay as '\n' on a
-    // roundtrip.
-    result = replaceAll(result, "\r\n", "\n");
-
-    return result;
-}
-
-// static
-std::string File::readToString(const std::string &filename)
-{
-    return readToString(filename.c_str());
-}
-
-// static
-void File::writeFileFromString(const std::string &filename,
-                               const std::string &text)
-{
-    File file(filename, "w");
-    file.writeString(text);
-    file.close();
-}
-
-} // namespace gmx
diff --git a/src/gromacs/utility/file.h b/src/gromacs/utility/file.h
deleted file mode 100644 (file)
index 9a6b956..0000000
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * This file is part of the GROMACS molecular simulation package.
- *
- * Copyright (c) 2012,2013,2014,2015, by the GROMACS development team, led by
- * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
- * and including many others, as listed in the AUTHORS file in the
- * top-level source directory and at http://www.gromacs.org.
- *
- * GROMACS is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public License
- * as published by the Free Software Foundation; either version 2.1
- * of the License, or (at your option) any later version.
- *
- * GROMACS is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with GROMACS; if not, see
- * http://www.gnu.org/licenses, or write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
- *
- * If you want to redistribute modifications to GROMACS, please
- * consider that scientific software is very special. Version
- * control is crucial - bugs must be traceable. We will be happy to
- * consider code for inclusion in the official distribution, but
- * derived work must not be called official GROMACS. Details are found
- * in the README & COPYING files - if they are missing, get the
- * official version at http://www.gromacs.org.
- *
- * To help us fund GROMACS development, we humbly ask that you cite
- * the research papers on the package. Check out http://www.gromacs.org.
- */
-/*! \file
- * \brief
- * Declares gmx::File.
- *
- * \author Teemu Murtola <teemu.murtola@gmail.com>
- * \inpublicapi
- * \ingroup module_utility
- */
-#ifndef GMX_UTILITY_FILE_H
-#define GMX_UTILITY_FILE_H
-
-#include <cstdio>
-
-#include <string>
-
-#include "gromacs/utility/classhelpers.h"
-
-namespace gmx
-{
-
-/*! \brief
- * Basic file object.
- *
- * This class provides basic file I/O functionality and uses exceptions
- * (FileIOError) for error reporting.
- *
- * \inpublicapi
- * \ingroup module_utility
- */
-class File
-{
-    public:
-        /*! \brief
-         * Opens a file and returns a `FILE` handle.
-         *
-         * \param[in] filename  Path of the file to open.
-         * \param[in] mode      Mode to open the file in (for fopen()).
-         * \throws    FileIOError on any I/O error.
-         *
-         * Instead of returning `NULL` on errors, throws an exception with
-         * additional details (including the file name and `errno`).
-         */
-        static FILE *openRawHandle(const char *filename, const char *mode);
-        //! \copydoc openRawHandle(const char *, const char *)
-        static FILE *openRawHandle(const std::string &filename, const char *mode);
-        /*! \brief
-         * Creates a file object and opens a file.
-         *
-         * \param[in] filename  Path of the file to open.
-         * \param[in] mode      Mode to open the file in (for fopen()).
-         * \throws    std::bad_alloc if out of memory.
-         * \throws    FileIOError on any I/O error.
-         *
-         * \see open(const char *, const char *)
-         */
-        File(const char *filename, const char *mode);
-        //! \copydoc File(const char *, const char *)
-        File(const std::string &filename, const char *mode);
-        /*! \brief
-         * Destroys the file object.
-         *
-         * If the file is still open, it is closed.
-         * Any error conditions will be ignored.
-         */
-        ~File();
-
-        /*! \brief
-         * Opens a file.
-         *
-         * \param[in] filename  Path of the file to open.
-         * \param[in] mode      Mode to open the file in (for fopen()).
-         * \throws    FileIOError on any I/O error.
-         *
-         * The file object must not be open.
-         */
-        void open(const char *filename, const char *mode);
-        //! \copydoc open(const char *, const char *)
-        void open(const std::string &filename, const char *mode);
-        /*! \brief
-         * Closes the file object.
-         *
-         * \throws  FileIOError on any I/O error.
-         *
-         * The file must be open.
-         */
-        void close();
-
-        /*! \brief
-         * Returns a file handle for interfacing with C functions.
-         *
-         * The file must be open.
-         * Does not throw.
-         */
-        FILE *handle();
-
-        /*! \brief
-         * Reads given number of bytes from the file.
-         *
-         * \param[out] buffer  Pointer to buffer that receives the bytes.
-         * \param[in]  bytes   Number of bytes to read.
-         * \throws     FileIOError on any I/O error.
-         *
-         * The file must be open.
-         */
-        void readBytes(void *buffer, size_t bytes);
-
-        /*! \brief
-         * Writes a string to the file.
-         *
-         * \param[in]  str  String to write.
-         * \throws     FileIOError on any I/O error.
-         *
-         * The file must be open.
-         */
-        void writeString(const char *str);
-        //! \copydoc writeString(const char *)
-        void writeString(const std::string &str) { writeString(str.c_str()); }
-
-        /*! \brief
-         * Checks whether a file exists and is a regular file.
-         *
-         * \param[in] filename  Path to the file to check.
-         * \returns   true if \p filename exists and is accessible.
-         *
-         * Does not throw.
-         */
-        static bool exists(const char *filename);
-        //! \copydoc exists(const char *)
-        static bool exists(const std::string &filename);
-
-        /*! \brief
-         * Reads contents of a file to a std::string.
-         *
-         * \param[in] filename  Name of the file to read.
-         * \returns   The contents of \p filename.
-         * \throws    std::bad_alloc if out of memory.
-         * \throws    FileIOError on any I/O error.
-         */
-        static std::string readToString(const char *filename);
-        //! \copydoc readToString(const char *)
-        static std::string readToString(const std::string &filename);
-        /*! \brief
-         * Convenience method for writing a file from a string in a single call.
-         *
-         * \param[in] filename  Name of the file to read.
-         * \param[in] text      String to write to \p filename.
-         * \throws    FileIOError on any I/O error.
-         *
-         * If \p filename exists, it is overwritten.
-         */
-        static void writeFileFromString(const std::string &filename,
-                                        const std::string &text);
-
-    private:
-        class Impl;
-
-        PrivateImplPointer<Impl> impl_;
-};
-
-} // namespace gmx
-
-#endif
index 054d7c649507bad3012fde869f5458a3c2d0259a..68e595c477d214a4a84019c2a03681639bdaa544 100644 (file)
@@ -43,8 +43,8 @@
 
 #include "fileredirector.h"
 
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/filestream.h"
+#include "gromacs/utility/path.h"
 
 namespace gmx
 {
index 7a2cf25dc716398ca5ad1e6d2eaf7eda6a49b09d..5f245858a5662fd6a0bace6138f10771179ad668 100644 (file)
@@ -188,6 +188,25 @@ StandardInputStream &StandardInputStream::instance()
  * TextInputFile
  */
 
+// static
+FILE *TextInputFile::openRawHandle(const char *filename)
+{
+    FILE *fp = fopen(filename, "r");
+    if (fp == NULL)
+    {
+        GMX_THROW_WITH_ERRNO(
+                FileIOError(formatString("Could not open file '%s'", filename)),
+                "fopen", errno);
+    }
+    return fp;
+}
+
+// static
+FILE *TextInputFile::openRawHandle(const std::string &filename)
+{
+    return openRawHandle(filename.c_str());
+}
+
 TextInputFile::TextInputFile(const std::string &filename)
     : impl_(new FileStreamImpl(filename.c_str(), "r"))
 {
index f1e49339ca21e7e0900ea65bc0422069045c0089..23c354c344166f3928b97e02e937440db3b6af6a 100644 (file)
@@ -103,6 +103,19 @@ class StandardInputStream : public TextInputStream
 class TextInputFile : public TextInputStream
 {
     public:
+        /*! \brief
+         * Opens a file and returns a `FILE` handle.
+         *
+         * \param[in] filename  Path of the file to open.
+         * \throws    FileIOError on any I/O error.
+         *
+         * Instead of returning `NULL` on errors, throws an exception with
+         * additional details (including the file name and `errno`).
+         */
+        static FILE *openRawHandle(const char *filename);
+        //! \copydoc openRawHandle(const char *, const char *)
+        static FILE *openRawHandle(const std::string &filename);
+
         /*! \brief
          * Opens a text file as a stream.
          *
index d6aa17140d65db27cd77cd0f31ef291dd0a6903a..60c0e0cd7adbb164f5c3a1ad20f47f7762e71b16 100644 (file)
 
 #include <cctype>
 #include <cerrno>
+#include <cstdio>
 #include <cstdlib>
 #include <cstring>
 
 #include <algorithm>
+#include <string>
 
 #include <sys/stat.h>
 
@@ -386,6 +388,44 @@ std::string Path::resolveSymlinks(const std::string &path)
     return result;
 }
 
+/********************************************************************
+ * File
+ */
+
+// static
+bool File::exists(const char *filename)
+{
+    if (filename == NULL)
+    {
+        return false;
+    }
+    FILE *test = std::fopen(filename, "r");
+    if (test == NULL)
+    {
+        return false;
+    }
+    else
+    {
+        std::fclose(test);
+        // Windows doesn't allow fopen of directory, so we don't need to check
+        // this separately.
+#ifndef GMX_NATIVE_WINDOWS
+        struct stat st_buf;
+        int         status = stat(filename, &st_buf);
+        if (status != 0 || !S_ISREG(st_buf.st_mode))
+        {
+            return false;
+        }
+#endif
+        return true;
+    }
+}
+
+// static
+bool File::exists(const std::string &filename)
+{
+    return exists(filename.c_str());
+}
 
 /********************************************************************
  * Directory
index ef2b3e884879ca7c7ecbc8ea4f282037379b8911..8dba41e84c0f1947cb21c62b907eb601e4ad911e 100644 (file)
@@ -85,6 +85,25 @@ class Path
         Path();
 };
 
+class File
+{
+    public:
+        /*! \brief
+         * Checks whether a file exists and is a regular file.
+         *
+         * \param[in] filename  Path to the file to check.
+         * \returns   `true` if \p filename exists and is accessible.
+         *
+         * Does not throw.
+         */
+        static bool exists(const char *filename);
+        //! \copydoc exists(const char *)
+        static bool exists(const std::string &filename);
+
+    private:
+        // Disallow instantiation.
+        File();
+};
 
 class Directory
 {
index 4eef63e4fc4d450c230faa719d1bd16d276a205a..436614964bb9cfea23ed3a83bb5b6e83572dae48 100644 (file)
 namespace gmx
 {
 
+// static
+std::string TextReader::readFileToString(const char *filename)
+{
+    std::string result;
+    TextReader  reader(filename);
+    std::string line;
+    while (reader.readLine(&line))
+    {
+        result.append(line);
+    }
+    reader.close();
+    return result;
+}
+
+// static
+std::string TextReader::readFileToString(const std::string &filename)
+{
+    return readFileToString(filename.c_str());
+}
+
 class TextReader::Impl
 {
     public:
index 0310f1a0618c847b965103a51a797ab4b4b2b606..62607c6499bebb7e11337eaf67d2c6cb6c972ffe 100644 (file)
@@ -67,6 +67,18 @@ namespace gmx
 class TextReader
 {
     public:
+        /*! \brief
+         * Reads contents of a file to a std::string.
+         *
+         * \param[in] filename  Name of the file to read.
+         * \returns   The contents of \p filename.
+         * \throws    std::bad_alloc if out of memory.
+         * \throws    FileIOError on any I/O error.
+         */
+        static std::string readFileToString(const char *filename);
+        //! \copydoc readFileToString(const char *)
+        static std::string readFileToString(const std::string &filename);
+
         /*! \brief
          * Creates a reader that reads from specified file.
          *
index aef0d5cc7b546d6a608f6c0ce9c19774ef656285..6e52e0a949c35c23d78f3331941b5ff71f84c011 100644 (file)
@@ -63,6 +63,15 @@ class TextWriter::Impl
         TextOutputStreamPointer stream_;
 };
 
+// static
+void TextWriter::writeFileFromString(const std::string &filename,
+                                     const std::string &text)
+{
+    TextWriter file(filename);
+    file.writeString(text);
+    file.close();
+}
+
 TextWriter::TextWriter(const std::string &filename)
     : impl_(new Impl(TextOutputStreamPointer(new TextOutputFile(filename))))
 {
index c473b8c279e63c7113047ea998ec8297e7709db8..de83c98d8a9e609d8d08b216a628a209c18e6b89 100644 (file)
@@ -66,6 +66,19 @@ namespace gmx
 class TextWriter
 {
     public:
+        /*! \brief
+         * Convenience method for writing a file from a string in a single call.
+         *
+         * \param[in] filename  Name of the file to read.
+         * \param[in] text      String to write to \p filename.
+         * \throws    std::bad_alloc if out of memory.
+         * \throws    FileIOError on any I/O error.
+         *
+         * If \p filename exists, it is overwritten.
+         */
+        static void writeFileFromString(const std::string &filename,
+                                        const std::string &text);
+
         /*! \brief
          * Creates a writer that writes to specified file.
          *
index 845aa58ac0fadebb683eebd647bb366c4567b342..b793af46c56d853cbbeb4e3a69ef496b1ca47ca3 100644 (file)
@@ -50,8 +50,8 @@
 #include "gromacs/options/options.h"
 #include "gromacs/utility/basedefinitions.h"
 #include "gromacs/utility/basenetwork.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/gmxmpi.h"
+#include "gromacs/utility/textwriter.h"
 #include "programs/mdrun/mdrun_main.h"
 
 #include "testutils/cmdlinetest.h"
@@ -133,13 +133,13 @@ SimulationRunner::useStringAsMdpFile(const char *mdpString)
 void
 SimulationRunner::useStringAsMdpFile(const std::string &mdpString)
 {
-    gmx::File::writeFileFromString(mdpInputFileName_, mdpString);
+    gmx::TextWriter::writeFileFromString(mdpInputFileName_, mdpString);
 }
 
 void
 SimulationRunner::useStringAsNdxFile(const char *ndxString)
 {
-    gmx::File::writeFileFromString(ndxFileName_, ndxString);
+    gmx::TextWriter::writeFileFromString(ndxFileName_, ndxString);
 }
 
 void
index af2e5b23908886a13bbc53a71936bd9c8aba9ba1..6b336b27f313f3cb8f4ba78760c3a1b8c1460bb7 100644 (file)
@@ -55,9 +55,9 @@
 #include "gromacs/commandline/cmdlineoptionsmodule.h"
 #include "gromacs/commandline/cmdlineprogramcontext.h"
 #include "gromacs/utility/arrayref.h"
-#include "gromacs/utility/file.h"
 #include "gromacs/utility/gmxassert.h"
 #include "gromacs/utility/stringutil.h"
+#include "gromacs/utility/textreader.h"
 #include "gromacs/utility/textwriter.h"
 
 #include "testutils/refdata.h"
@@ -298,7 +298,7 @@ void CommandLineTestHelper::setInputFileContents(
     GMX_ASSERT(extension[0] != '.', "Extension should not contain a dot");
     std::string fullFilename = impl_->fileManager_.getTemporaryFilePath(
                 formatString("%d.%s", args->argc(), extension));
-    File::writeFileFromString(fullFilename, contents);
+    TextWriter::writeFileFromString(fullFilename, contents);
     args->addOption(option, fullFilename);
 }
 
@@ -346,7 +346,7 @@ void CommandLineTestHelper::checkOutputFiles(TestReferenceChecker checker) const
              outfile != impl_->outputFiles_.end();
              ++outfile)
         {
-            std::string output = File::readToString(outfile->path);
+            std::string output = TextReader::readFileToString(outfile->path);
             outputChecker.checkStringBlock(output, outfile->option.c_str());
         }
     }
index 20fa85f566a0159ee8007e9fe9290f90fca5c850..9913f6053ee00b7ff7e115d0596b669d8434aa62 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * This file is part of the GROMACS molecular simulation package.
  *
- * Copyright (c) 2013,2014, by the GROMACS development team, led by
+ * Copyright (c) 2013,2014,2015, by the GROMACS development team, led by
  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
  * and including many others, as listed in the AUTHORS file in the
  * top-level source directory and at http://www.gromacs.org.
@@ -46,7 +46,7 @@
 #include <stdio.h>
 
 #include "gromacs/utility/exceptions.h"
-#include "gromacs/utility/file.h"
+#include "gromacs/utility/textwriter.h"
 
 namespace gmx
 {
@@ -69,7 +69,7 @@ void
 IntegrationTestFixture::redirectStringToStdin(const char* theString)
 {
     std::string fakeStdin("fake-stdin");
-    gmx::File::writeFileFromString(fakeStdin, theString);
+    gmx::TextWriter::writeFileFromString(fakeStdin, theString);
     if (NULL == std::freopen(fakeStdin.c_str(), "r", stdin))
     {
         GMX_THROW_WITH_ERRNO(FileIOError("Failed to redirect a string to stdin"),
index 8c005295e04c1e764b5e06950d768e27924abe7a..ce37bdfee5f873631851795b37dd32500df8ea05 100644 (file)
@@ -49,7 +49,7 @@
 
 #include "gromacs/options/basicoptions.h"
 #include "gromacs/options/options.h"
-#include "gromacs/utility/file.h"
+#include "gromacs/utility/textreader.h"
 
 #include "testutils/refdata.h"
 #include "testutils/testoptions.h"
@@ -136,7 +136,7 @@ StringTestBase::checkText(const std::string &text, const char *id)
 void
 StringTestBase::checkFileContents(const std::string &filename, const char *id)
 {
-    const std::string text = File::readToString(filename);
+    const std::string text = TextReader::readFileToString(filename);
     checkText(text, id);
 }