Check result of fread
[yaz-moved-to-github.git] / util / yaz-url.c
index 9cdb388..ed5d8bb 100644 (file)
@@ -1,10 +1,10 @@
 /* This file is part of the YAZ toolkit.
- * Copyright (C) 1995-2011 Index Data
+ * Copyright (C) 1995-2012 Index Data
  * See the file LICENSE for details.
  */
 
 #if HAVE_CONFIG_H
-#include "config.h"
+#include <config.h>
 #endif
 
 #include <string.h>
 static void usage(void)
 {
     printf("yaz-icu [options] url ..\n");
-    printf(" -H name:value       Set HTTP header (repeat if necessary)\n");
-    printf(" -m method           HTTP method\n");
-    printf(" -p file             POSTs file at following url\n");
-    printf(" -u user/password    Basic HTTP auth\n");
-    printf(" -x proxy            HTTP proxy\n");
+    printf(" -H name:value       Sets HTTP header (repeat if necessary)\n");
+    printf(" -m method           Sets HTTP method\n");
+    printf(" -O fname            Writes HTTP content to file\n");
+    printf(" -p fname            POSTs file at following url\n");
+    printf(" -u user/password    Sets Basic HTTP auth\n");
+    printf(" -x proxy            Sets HTTP proxy\n");
     exit(1);
 }
 
@@ -44,7 +45,12 @@ static char *get_file(const char *fname, size_t *len)
     {
         buf = xmalloc(*len);
         fseek(inf, 0L, SEEK_SET);
-        fread(buf, 1, *len, inf);
+        size_t r = fread(buf, 1, *len, inf);
+        if (r != *len)
+        {
+            yaz_log(YLOG_FATAL|YLOG_ERRNO, "short fread of %s", fname);
+            exit(1);
+        }
     }
     fclose(inf);
     return buf;
@@ -63,8 +69,9 @@ int main(int argc, char **argv)
     ODR odr = odr_createmem(ODR_ENCODE);
     int exit_code = 0;
     int no_urls = 0;
+    const char *outfname = 0;
 
-    while ((ret = options("hH:m:p:u:x:", argv, argc, &arg))
+    while ((ret = options("hH:m:O:p:u:x:", argv, argc, &arg))
            != YAZ_OPTIONS_EOF)
     {
         switch (ret)
@@ -93,6 +100,9 @@ int main(int argc, char **argv)
         case 'm':
             method = arg;
             break;
+        case 'O':
+            outfname = arg;
+            break;
         case 'p':
             xfree(post_buf);
             post_buf = get_file(arg, &post_len);
@@ -122,8 +132,20 @@ int main(int argc, char **argv)
                 exit_code = 1;
             else
             {
+                FILE *outf = stdout;
+                if (outfname)
+                {
+                    outf = fopen(outfname, "w");
+                    if (!outf)
+                    {
+                        yaz_log(YLOG_FATAL|YLOG_ERRNO, "open %s", outfname);
+                        exit(1);
+                    }
+                }
                 fwrite(http_response->content_buf, 1,
-                       http_response->content_len, stdout);
+                       http_response->content_len, outf);
+                if (outfname)
+                    fclose(outf);
             }
             no_urls++;
             break;