bam_cat.c:
[samtools.git] / bam_cat.c
index 0fde045e1c6e319594c3453a6cdd6a1fac21e335..43df91702e8cdb96f3af4f9e4d62f51e96e77e9d 100644 (file)
--- a/bam_cat.c
+++ b/bam_cat.c
@@ -86,7 +86,10 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam
     }\r
     if (h) bam_header_write(fp, h);\r
     \r
-    buf = (uint8_t*) malloc(BUF_SIZE);\r
+    if ((buf = (uint8_t*) malloc(BUF_SIZE)) == NULL) {\r
+        fprintf(stderr, "[%s] failed to allocate input buffer.\n", __func__);\r
+        return -1;\r
+    }\r
     for(i = 0; i < nfn; ++i){\r
         BGZF *in;\r
         bam_header_t *old;\r
@@ -121,14 +124,26 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam
                     fprintf(stderr, "[%s] ERROR: truncated file?: '%s'.\n", __func__, fn[i]);\r
                     return -1;\r
                 }\r
-                fwrite(ebuf, 1, len, fp_file);\r
+                if (fwrite(ebuf, 1, len, fp_file) < len) {\r
+                    fprintf(stderr, "[%s] failed to write to output file.\n", __func__);\r
+                    return -1;\r
+               }\r
                 memcpy(ebuf,ebuf+len,diff);\r
                 memcpy(ebuf+diff,buf,len);\r
-            } else {\r
-                if(j!=0) fwrite(ebuf, 1, es, fp_file);\r
+            }\r
+            else {\r
+                if(j!=0) {\r
+                    if (fwrite(ebuf, 1, es, fp_file) < es) {\r
+                        fprintf(stderr, "[%s] failed to write to output file.\n", __func__);\r
+                        return -1;\r
+                    }\r
+                }\r
                 len-= es;\r
                 memcpy(ebuf,buf+len,es);\r
-                fwrite(buf, 1, len, fp_file);\r
+                if (fwrite(buf, 1, len, fp_file) < len) {\r
+                    fprintf(stderr, "[%s] failed to write to output file.\n", __func__);\r
+                    return -1;\r
+                }\r
             }\r
             j=1;\r
         }\r
@@ -141,7 +156,9 @@ int bam_cat(int nfn, char * const *fn, const bam_header_t *h, const char* outbam
             if(((gzip1!=GZIPID1) || (gzip2!=GZIPID2)) || (isize!=0)) {\r
                 fprintf(stderr, "[%s] WARNING: Unexpected block structure in file '%s'.", __func__, fn[i]);\r
                 fprintf(stderr, " Possible output corruption.\n");\r
-                fwrite(ebuf, 1, es, fp_file);\r
+                if (fwrite(ebuf, 1, es, fp_file) < es) {\r
+                    fprintf(stderr, " Also, failed to write final block.\n");\r
+                }\r
             }\r
         }\r
         bam_header_destroy(old);\r