How to fix corrupted file from FTP transfer

Sometimes it happens.  I intend to send a binary file to an FTP server and forget to change the mode to BINARY before starting the transfer.
It’s really easy to do… and it was a natural habit type of thing back in the day when I used FTP frequently…
ftp www.xyz.com
user
pass
hash
binary
Simple and straight forward.  Anyway, I screwed up the other day and thought all was lost after a few .tgz files I transferred over to a server via FTP were not extractable.  I deleted my source before verifying my file transfers, stupid me.
Anyway, a tool that worked like a champ, Windows and Linux, is fixgz.  fixgz attempts to fix a binary file transferred in ascii mode by
* removing each extra CR when it followed by LF.  So if you ever get a corrupted file after transferring via FTP in the wrong format, give this a whirl.
fixgz.c

/* fixgz attempts to fix a binary file transferred in ascii mode by
 * removing each extra CR when it followed by LF.
 * usage: fixgz  bad.gz fixed.gz
 * WARNING: the output file name must be different from the input file name!
 * Copyright 1998 Jean-loup Gailly <jloup@gzip.org>
 *   This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the author be held liable for any damages
 * arising from the use of this software.
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely.
 */
#include
int main(argc, argv)
     int argc;
     char **argv;
{
    int c1, c2; /* input bytes */
    FILE *in;   /* corrupted input file */
    FILE *out;  /* fixed output file */
    if (argc <= 2) {
	fprintf(stderr, "usage: fixgz bad.gz fixed.gz
");
	exit(1);
    }
    if (!strcmp(argv[1], argv[2])) {
	fprintf(stderr, "input and output files must be different
");
	exit(1);
    }
    in  = fopen(argv[1], "rb");
    if (in == NULL) {
	fprintf(stderr, "fixgz: cannot open %s
", argv[1]);
	exit(1);
    }
    out = fopen(argv[2], "wb");
    if (in == NULL) {
	fprintf(stderr, "fixgz: cannot create %s
", argv[2]);
	exit(1);
    }
    c1 = fgetc(in);
    while ((c2 = fgetc(in)) != EOF) {
	if (c1 != '
' || c2 != '
') {
	    fputc(c1, out);
	}
	c1 = c2;
    }
    if (c1 != EOF) {
	fputc(c1, out);
    }
    exit(0);
    return 0; /* avoid warning */
}

Published by

Rich

Just another IT guy.

Leave a Reply

Your email address will not be published. Required fields are marked *