(svn r28004) -Update from Eints:
[openttd.git] / os / dos / exe2coff / exe2coff.c
blobaa072e8e41fc08a5825b487a7a308212a4fbed77
1 /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
2 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
3 /* Updated 2008 to use fread/fopen and friends instead of read/open so it compiles with GCC on Unix (Rubidium) */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <fcntl.h>
7 #include <sys/stat.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <ctype.h>
13 static void
14 exe2aout(char *fname)
16 unsigned short header[3];
17 FILE *ifile;
18 FILE *ofile;
19 char buf[4096];
20 int rbytes;
21 char *dot = strrchr(fname, '.');
22 if (!dot || strlen(dot) != 4
23 || tolower(dot[1]) != 'e'
24 || tolower(dot[2]) != 'x'
25 || tolower(dot[3]) != 'e')
27 fprintf(stderr, "%s: Arguments MUST end with a .exe extension\n", fname);
28 return;
31 ifile = fopen(fname, "rb");
32 if (!ifile)
34 perror(fname);
35 return;
37 fread(header, sizeof(header), 1, ifile);
38 if (header[0] == 0x5a4d)
40 long header_offset = (long)header[2]*512L;
41 if (header[1])
42 header_offset += (long)header[1] - 512L;
43 fseek(ifile, header_offset, SEEK_SET);
44 header[0] = 0;
45 fread(header, sizeof(header), 1, ifile);
46 if ((header[0] != 0x010b) && (header[0] != 0x014c))
48 fprintf(stderr, "`%s' does not have a COFF/AOUT program appended to it\n", fname);
49 return;
51 fseek(ifile, header_offset, SEEK_SET);
53 else
55 fprintf(stderr, "`%s' is not an .EXE file\n", fname);
56 return;
59 *dot = 0;
60 ofile = fopen(fname, "w+b");
61 if (!ofile)
63 perror(fname);
64 return;
67 while ((rbytes=fread(buf, 1, 4096, ifile)) > 0)
69 int wb = fwrite(buf, 1, rbytes, ofile);
70 if (wb < 0)
72 perror(fname);
73 break;
75 if (wb < rbytes)
77 fprintf(stderr, "`%s': disk full\n", fname);
78 exit(1);
81 fclose(ifile);
82 fclose(ofile);
85 int
86 main(int argc, char **argv)
88 int i;
89 if (argc == 1) printf("Usage: %s <exename>", argv[0]);
90 for (i=1; i<argc; i++)
91 exe2aout(argv[i]);
92 return 0;