2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
37 #include "gromacs/utility/futil.h"
47 #include <sys/types.h>
60 #ifdef GMX_NATIVE_WINDOWS
65 /* Windows file stuff, only necessary for visual studio */
70 #include "thread_mpi/threads.h"
72 #include "gromacs/utility/cstringutil.h"
73 #include "gromacs/utility/exceptions.h"
74 #include "gromacs/utility/fatalerror.h"
75 #include "gromacs/utility/path.h"
76 #include "gromacs/utility/programcontext.h"
77 #include "gromacs/utility/smalloc.h"
78 #include "gromacs/utility/stringutil.h"
80 /* we keep a linked list of all files opened through pipes (i.e.
81 compressed or .gzipped files. This way we can distinguish between them
82 without having to change the semantics of reading from/writing to files)
84 typedef struct t_pstack {
86 struct t_pstack *prev;
89 static t_pstack *pstack = NULL;
90 static gmx_bool bUnbuffered = FALSE;
92 /* this linked list is an intrinsically globally shared object, so we have
93 to protect it with mutexes */
94 static tMPI_Thread_mutex_t pstack_mutex = TMPI_THREAD_MUTEX_INITIALIZER;
101 void push_ps(FILE *fp)
105 tMPI_Thread_mutex_lock(&pstack_mutex);
112 tMPI_Thread_mutex_unlock(&pstack_mutex);
116 /* don't use pipes!*/
117 #define popen fah_fopen
118 #define pclose fah_fclose
124 #if (!defined(HAVE_PIPES) && !defined(__native_client__))
125 static FILE *popen(const char *nm, const char *mode)
127 gmx_impl("Sorry no pipes...");
132 static int pclose(FILE *fp)
134 gmx_impl("Sorry no pipes...");
138 #endif /* !defined(HAVE_PIPES) && !defined(__native_client__) */
139 #endif /* GMX_FAHCORE */
141 int gmx_ffclose(FILE *fp)
149 tMPI_Thread_mutex_lock(&pstack_mutex);
159 else if (ps->fp == fp)
165 pstack = pstack->prev;
170 while ((ps->prev != NULL) && (ps->prev->fp != fp))
174 if ((ps->prev != NULL) && ps->prev->fp == fp)
176 if (ps->prev->fp != NULL)
178 ret = pclose(ps->prev->fp);
181 ps->prev = ps->prev->prev;
193 tMPI_Thread_mutex_unlock(&pstack_mutex);
199 void frewind(FILE *fp)
201 tMPI_Thread_mutex_lock(&pstack_mutex);
203 t_pstack *ps = pstack;
208 fprintf(stderr, "Cannot rewind compressed file!\n");
209 tMPI_Thread_mutex_unlock(&pstack_mutex);
215 tMPI_Thread_mutex_unlock(&pstack_mutex);
218 int gmx_fseek(FILE *stream, gmx_off_t offset, int whence)
221 return fseeko(stream, offset, whence);
223 #ifdef HAVE__FSEEKI64
224 return _fseeki64(stream, offset, whence);
226 return fseek(stream, offset, whence);
231 gmx_off_t gmx_ftell(FILE *stream)
234 return ftello(stream);
236 #ifdef HAVE__FSEEKI64
237 return _ftelli64(stream);
239 return ftell(stream);
245 //! Check whether the file (opened by gmx_ffopen()) is a pipe.
246 static bool is_pipe(FILE *fp)
248 tMPI_Thread_mutex_lock(&pstack_mutex);
250 t_pstack *ps = pstack;
255 tMPI_Thread_mutex_unlock(&pstack_mutex);
260 tMPI_Thread_mutex_unlock(&pstack_mutex);
265 static FILE *uncompress(const char *fn, const char *mode)
270 sprintf(buf, "uncompress -c < %s", fn);
271 fprintf(stderr, "Going to execute '%s'\n", buf);
272 if ((fp = popen(buf, mode)) == NULL)
281 static FILE *gunzip(const char *fn, const char *mode)
286 sprintf(buf, "gunzip -c < %s", fn);
287 fprintf(stderr, "Going to execute '%s'\n", buf);
288 if ((fp = popen(buf, mode)) == NULL)
297 gmx_bool gmx_fexist(const char *fname)
305 test = fopen(fname, "r");
308 /*Windows doesn't allow fopen of directory - so we need to check this seperately */
309 #ifdef GMX_NATIVE_WINDOWS
310 DWORD attr = GetFileAttributes(fname);
311 return (attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY);
323 gmx_bool gmx_eof(FILE *fp)
334 if ((beof = fread(data, 1, 1, fp)) == 1)
336 gmx_fseek(fp, -1, SEEK_CUR);
342 static char *backup_fn(const char *file, int count_max)
344 /* Use a reasonably low value for countmax; we might
345 * generate 4-5 files in each round, and we dont
346 * want to hit directory limits of 1024 or 2048 files.
350 char *directory, *fn;
355 count_max = COUNTMAX;
358 smalloc(buf, GMX_PATH_MAX);
360 for (i = strlen(file)-1; ((i > 0) && (file[i] != DIR_SEPARATOR)); i--)
364 /* Must check whether i > 0, i.e. whether there is a directory
365 * in the file name. In that case we overwrite the / sign with
366 * a '\0' to end the directory string .
370 directory = gmx_strdup(file);
372 fn = gmx_strdup(file+i+1);
376 directory = gmx_strdup(".");
377 fn = gmx_strdup(file);
381 sprintf(buf, "%s/#%s.%d#", directory, fn, count);
384 while ((count <= count_max) && gmx_fexist(buf));
386 /* Arbitrarily bail out */
387 if (count > count_max)
389 gmx_fatal(FARGS, "Won't make more than %d backups of %s for you.\n"
390 "The env.var. GMX_MAXBACKUP controls this maximum, -1 disables backups.",
400 gmx_bool make_backup(const char * name)
407 return FALSE; /* skip making backups */
410 if (gmx_fexist(name))
412 env = getenv("GMX_MAXBACKUP");
415 count_max = strtol(env, NULL, 10);
418 /* Do not make backups and possibly overwrite old files */
424 /* Use the default maximum */
427 backup = backup_fn(name, count_max);
428 if (rename(name, backup) == 0)
430 fprintf(stderr, "\nBack Off! I just backed up %s to %s\n",
435 fprintf(stderr, "Sorry couldn't backup %s to %s\n", name, backup);
444 FILE *gmx_ffopen(const char *file, const char *mode)
447 return fopen(file, mode);
450 char buf[256], *bufsize = 0, *ptr;
465 bRead = (mode[0] == 'r' && mode[1] != '+');
467 if (!bRead || gmx_fexist(buf))
469 if ((ff = fopen(buf, mode)) == NULL)
474 /* Check whether we should be using buffering (default) or not
477 if (bUnbuffered || ((bufsize = getenv("LOG_BUFS")) != NULL))
479 /* Check whether to use completely unbuffered */
486 bs = strtol(bufsize, NULL, 10);
495 if (setvbuf(ff, ptr, _IOFBF, bs) != 0)
497 gmx_file("Buffering File");
505 sprintf(buf, "%s.Z", file);
508 ff = uncompress(buf, mode);
512 sprintf(buf, "%s.gz", file);
515 ff = gunzip(buf, mode);
527 /* Our own implementation of dirent-like functionality to scan directories. */
532 #elif (defined GMX_NATIVE_WINDOWS)
533 intptr_t windows_handle;
534 struct _finddata_t finddata;
543 gmx_directory_open(gmx_directory_t *p_gmxdir, const char *dirname)
545 struct gmx_directory * gmxdir;
553 if ( (gmxdir->dirent_handle = opendir(dirname)) != NULL)
563 #elif (defined GMX_NATIVE_WINDOWS)
565 if (dirname != NULL && strlen(dirname) > 0)
570 len = strlen(dirname);
571 snew(tmpname, len+3);
573 strncpy(tmpname, dirname, len+1);
575 /* Remove possible trailing directory separator */
576 if (tmpname[len] == '/' || tmpname[len] == '\\')
582 strcat(tmpname, "/*");
585 if ( (gmxdir->windows_handle = _findfirst(tmpname, &gmxdir->finddata)) > 0L)
609 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n"
610 "In the very unlikely event this is not a compile-time mistake you could consider\n"
611 "implementing support for your platform in futil.c, but contact the developers\n"
612 "to make sure it's really necessary!\n");
620 gmx_directory_nextfile(gmx_directory_t gmxdir, char *name, int maxlength_name)
626 struct dirent * direntp_large;
630 if (gmxdir != NULL && gmxdir->dirent_handle != NULL)
632 /* On some platforms no space is present for d_name in dirent.
633 * Since d_name is guaranteed to be the last entry, allocating
634 * extra space for dirent will allow more size for d_name.
635 * GMX_MAX_PATH should always be >= the max possible d_name.
637 smalloc(direntp_large, sizeof(*direntp_large) + GMX_PATH_MAX);
638 rc = readdir_r(gmxdir->dirent_handle, direntp_large, &p);
640 if (p != NULL && rc == 0)
642 strncpy(name, direntp_large->d_name, maxlength_name);
649 sfree(direntp_large);
657 #elif (defined GMX_NATIVE_WINDOWS)
661 if (gmxdir->windows_handle <= 0)
667 else if (gmxdir->first == 1)
669 strncpy(name, gmxdir->finddata.name, maxlength_name);
675 if (_findnext(gmxdir->windows_handle, &gmxdir->finddata) == 0)
677 strncpy(name, gmxdir->finddata.name, maxlength_name);
690 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
698 gmx_directory_close(gmx_directory_t gmxdir)
702 rc = (gmxdir != NULL) ? closedir(gmxdir->dirent_handle) : EINVAL;
703 #elif (defined GMX_NATIVE_WINDOWS)
704 rc = (gmxdir != NULL) ? _findclose(gmxdir->windows_handle) : EINVAL;
707 "Source compiled without POSIX dirent or windows support - cannot scan directories.\n");
716 char *low_gmxlibfn(const char *file, gmx_bool bAddCWD, gmx_bool bFatal)
718 bool bEnvIsSet = false;
721 if (bAddCWD && gmx_fexist(file))
723 return gmx_strdup(file);
728 // GMXLIB can be a path.
729 const char *lib = getenv("GMXLIB");
737 libpath = gmx::getProgramContext().defaultLibraryDataPath();
740 std::vector<std::string> pathEntries;
741 gmx::Path::splitPathEnvironment(libpath, &pathEntries);
742 std::vector<std::string>::const_iterator i;
743 for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
745 std::string testPath = gmx::Path::join(*i, file);
746 if (gmx::Path::exists(testPath))
748 return gmx_strdup(testPath.c_str());
753 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
759 "Library file %s not found %sin your GMXLIB path.",
760 file, bAddCWD ? "in current dir nor " : "");
765 "Library file %s not found %sin default directories.\n"
766 "(You can set the directories to search with the GMXLIB path variable)",
767 file, bAddCWD ? "in current dir nor " : "");
773 FILE *low_libopen(const char *file, gmx_bool bFatal)
778 fn = low_gmxlibfn(file, TRUE, bFatal);
788 fprintf(debug, "Opening library file %s\n", fn);
797 char *gmxlibfn(const char *file)
799 return low_gmxlibfn(file, TRUE, TRUE);
802 FILE *libopen(const char *file)
804 return low_libopen(file, TRUE);
807 void gmx_tmpnam(char *buf)
811 if ((len = strlen(buf)) < 7)
813 gmx_fatal(FARGS, "Buf passed to gmx_tmpnam must be at least 7 bytes long");
815 for (i = len-6; (i < len); i++)
819 /* mktemp is dangerous and we should use mkstemp instead, but
820 * since windows doesnt support it we have to separate the cases.
821 * 20090307: mktemp deprecated, use iso c++ _mktemp instead.
823 #ifdef GMX_NATIVE_WINDOWS
826 int fd = mkstemp(buf);
831 gmx_fatal(FARGS, "Invalid template %s for mkstemp", buf);
834 gmx_fatal(FARGS, "mkstemp created existing file", buf);
837 gmx_fatal(FARGS, "Permission denied for opening %s", buf);
844 /* name in Buf should now be OK */
847 int gmx_file_rename(const char *oldname, const char *newname)
849 #ifndef GMX_NATIVE_WINDOWS
850 /* under unix, rename() is atomic (at least, it should be). */
851 return rename(oldname, newname);
853 if (MoveFileEx(oldname, newname,
854 MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH))
865 int gmx_file_copy(const char *oldname, const char *newname, gmx_bool copy_if_empty)
867 /* the full copy buffer size: */
868 #define FILECOPY_BUFSIZE (1<<16)
873 snew(buf, FILECOPY_BUFSIZE);
875 in = fopen(oldname, "rb");
881 /* If we don't copy when empty, we postpone opening the file
882 until we're actually ready to write. */
885 out = fopen(newname, "wb");
896 nread = fread(buf, sizeof(char), FILECOPY_BUFSIZE, in);
902 /* so this is where we open when copy_if_empty is false:
903 here we know we read something. */
904 out = fopen(newname, "wb");
910 ret = fwrite(buf, sizeof(char), nread, out);
936 #undef FILECOPY_BUFSIZE
940 int gmx_fsync(FILE *fp)
945 /* the fahcore defines its own os-independent fsync */
947 #else /* GMX_FAHCORE */
951 /* get the file number */
952 #if defined(HAVE_FILENO)
954 #elif defined(HAVE__FILENO)
958 /* do the actual fsync */
961 #if (defined(HAVE_FSYNC))
963 #elif (defined(HAVE__COMMIT))
968 #endif /* GMX_FAHCORE */
970 /* We check for these error codes this way because POSIX requires them
971 to be defined, and using anything other than macros is unlikely: */
973 /* we don't want to report an error just because fsync() caught a signal.
974 For our purposes, we can just ignore this. */
975 if (rc && errno == EINTR)
981 /* we don't want to report an error just because we tried to fsync()
982 stdout, a socket or a pipe. */
983 if (rc && errno == EINVAL)
991 void gmx_chdir(const char *directory)
993 #ifdef GMX_NATIVE_WINDOWS
994 int rc = _chdir(directory);
996 int rc = chdir(directory);
1000 gmx_fatal(FARGS, "Cannot change directory to '%s'. Reason: %s",
1001 directory, strerror(errno));
1005 void gmx_getcwd(char *buffer, size_t size)
1007 #ifdef GMX_NATIVE_WINDOWS
1008 char *pdum = _getcwd(buffer, size);
1010 char *pdum = getcwd(buffer, size);
1014 gmx_fatal(FARGS, "Cannot get working directory. Reason: %s",