]> mj.ucw.cz Git - libucw.git/blobdiff - lib/fb-file.c
simplified usage of Log & Die
[libucw.git] / lib / fb-file.c
index 169f25e1a027ac858600b3824a7015a12994fbc7..a7290cbf8688f9de261a38c4e50dbb9584eee91e 100644 (file)
@@ -1,8 +1,7 @@
 /*
- *     Sherlock Library -- Fast Buffered I/O on Files
+ *     UCW Library -- Fast Buffered I/O on Files
  *
  *     (c) 1997--2004 Martin Mares <mj@ucw.cz>
- *     (c) 2004 Robert Spalek <robert@ucw.cz>
  *
  *     This software may be freely distributed and used according to the terms
  *     of the GNU Lesser General Public License.
 #include "lib/fastbuf.h"
 #include "lib/lfs.h"
 
-#include <stdlib.h>
+#include <stdio.h>
 #include <string.h>
 #include <fcntl.h>
 #include <unistd.h>
 
 struct fb_file {
   struct fastbuf fb;
-  int fd;                              /* File descriptor, -1 if not a real file */
+  int fd;                              /* File descriptor */
   int is_temp_file;                    /* 0=normal file, 1=temporary file, delete on close, -1=shared FD */
 };
 #define FB_FILE(f) ((struct fb_file *)(f)->is_fastbuf)
@@ -55,18 +54,14 @@ bfd_spout(struct fastbuf *f)
   f->bptr = f->buffer = FB_BUFFER(f);
 }
 
-static void
+static int
 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
 {
-  sh_off_t l;
-
-  if (whence == SEEK_SET && pos == f->pos)
-    return;
-
-  l = sh_seek(FB_FILE(f)->fd, pos, whence);
+  sh_off_t l = sh_seek(FB_FILE(f)->fd, pos, whence);
   if (l < 0)
-    die("lseek on %s: %m", f->name);
+    return 0;
   f->pos = l;
+  return 1;
 }
 
 static void
@@ -120,20 +115,26 @@ bfdopen_internal(int fd, uns buflen, byte *name)
 }
 
 struct fastbuf *
-bopen(byte *name, uns mode, uns buflen)
+bopen_try(byte *name, uns mode, uns buflen)
 {
-  struct fastbuf *b;
-  int fd;
+  int fd = sh_open(name, mode, 0666);
+  if (fd < 0)
+    return NULL;
+  struct fastbuf *b = bfdopen_internal(fd, buflen, name);
+  if (mode & O_APPEND)
+    bfd_seek(b, 0, SEEK_END);
+  return b;
+}
 
+struct fastbuf *
+bopen(byte *name, uns mode, uns buflen)
+{
   if (!buflen)
     return bopen_mm(name, mode);
-  fd = sh_open(name, mode, 0666);
-  if (fd < 0)
+  struct fastbuf *b = bopen_try(name, mode, buflen);
+  if (!b)
     die("Unable to %s file %s: %m",
        (mode & O_CREAT) ? "create" : "open", name);
-  b = bfdopen_internal(fd, buflen, name);
-  if (mode & O_APPEND)
-    bfd_seek(b, 0, SEEK_END);
   return b;
 }
 
@@ -154,9 +155,17 @@ bfdopen_shared(int fd, uns buflen)
   return f;
 }
 
+void
+bfilesync(struct fastbuf *b)
+{
+  bflush(b);
+  if (fsync(FB_FILE(b)->fd) < 0)
+    log(L_ERROR, "fsync(%s) failed: %m", b->name);
+}
+
 #ifdef TEST
 
-int main(int argc, char **argv)
+int main(int argc UNUSED, char **argv UNUSED)
 {
   struct fastbuf *f, *t;