librsync  2.0.1
fileutil.c
1 /*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
2  *
3  * librsync -- library for network deltas
4  *
5  * Copyright (C) 1999, 2000, 2001 by Martin Pool <mbp@sourcefrog.net>
6  * Copyright (C) 1999 by Andrew Tridgell <tridge@samba.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22 
23 #include "config.h"
24 
25 #include <assert.h>
26 #include <stdlib.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <stdio.h>
31 #ifdef HAVE_FCNTL_H
32 #include <fcntl.h>
33 #endif
34 #ifdef HAVE_SYS_FILE_H
35 #include <sys/file.h>
36 #endif
37 #include <string.h>
38 #include <errno.h>
39 
40 #include "librsync.h"
41 #include "fileutil.h"
42 #include "trace.h"
43 
44 
45 /**
46  * \brief Open a file, with special handling for `-' or unspecified
47  * parameters on input and output.
48  *
49  * \param fopen-style mode string.
50  */
51 FILE *
52 rs_file_open(char const *filename, char const *mode, int force)
53 {
54  FILE *f;
55  int is_write;
56 
57  is_write = mode[0] == 'w';
58 
59  if (!filename || !strcmp("-", filename)) {
60  if (is_write) {
61 #if _WIN32
62  _setmode(_fileno(stdout), _O_BINARY);
63 #endif
64  return stdout;
65  } else {
66 #if _WIN32
67  _setmode(_fileno(stdin), _O_BINARY);
68 #endif
69  return stdin;
70  }
71  }
72 
73  if (!force && is_write) {
74  if ((f = fopen(filename, "rb"))) {
75  // File exists
76  rs_error("File exists \"%s\", aborting!", filename);
77  fclose(f);
78  exit(RS_IO_ERROR);
79  }
80  }
81 
82  if (!(f = fopen(filename, mode))) {
83  rs_error("Error opening \"%s\" for %s: %s", filename,
84  is_write ? "write" : "read",
85  strerror(errno));
86  exit(RS_IO_ERROR);
87  }
88 
89  return f;
90 }
91 
92 int rs_file_close(FILE * f)
93 {
94  if ((f == stdin) || (f == stdout)) return 0;
95  return fclose(f);
96 }
Error in file or network IO.
Definition: librsync.h:203
Public header for librsync.