| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
| 4 | #include "common.h" |
| 5 | |
| 6 | const char *sofname = "adda"; |
| 7 | const char *syoumei = "Amiga/MacOS 9 to DOS, DOS to Amiga/MacOS 9"; |
| 8 | |
| 9 | void amiga_to_dos(FILE *in, FILE *out) { |
| 10 | int c; |
| 11 | |
| 12 | while ((c = fgetc(in)) != EOF) { |
| 13 | if (c != '\r') { |
| 14 | fputc(c, out); |
| 15 | } |
| 16 | if ((c = fgetc(in)) != '\n') { |
| 17 | fputc('\r', out); |
| 18 | fputc('\n', out); |
| 19 | ungetc(c, in); |
| 20 | } else { |
| 21 | fputc('\r', out); |
| 22 | fputc('\n', out); |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | void dos_to_amiga(FILE *in, FILE *out) { |
| 28 | int c; |
| 29 | int last_char = '\0'; |
| 30 | |
| 31 | while ((c = fgetc(in)) != EOF) { |
| 32 | if (last_char == '\r' && c == '\n') continue; |
| 33 | if (last_char != '\r' && c == '\n') fputc('\r', out); |
| 34 | else fputc(c, out); |
| 35 | last_char = c; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | int detect_line_ending(FILE *in) { |
| 40 | int c; |
| 41 | int islf = 0; |
| 42 | int iscr = 0; |
| 43 | while ((c = fgetc(in)) != EOF) { |
| 44 | if (c == '\r') iscr = 1; |
| 45 | if (c == '\n') islf = 1; |
| 46 | } |
| 47 | if (iscr && islf) return 1; |
| 48 | return 0; |
| 49 | } |
| 50 | |
| 51 | void usage() { |
| 52 | fprintf(stderr, "%s-%s\n%s\n", sofname, version, syoumei); |
| 53 | fprintf(stderr, "usage: %s <ファイル.txt>\n", sofname); |
| 54 | } |
| 55 | |
| 56 | int main(int argc, char *argv[]) { |
| 57 | if (argc != 2) { |
| 58 | usage(); |
| 59 | return 1; |
| 60 | } |
| 61 | |
| 62 | FILE *in = fopen(argv[1], "r"); |
| 63 | if (in == NULL) { |
| 64 | perror("fopen input"); |
| 65 | usage(); |
| 66 | return 1; |
| 67 | } |
| 68 | |
| 69 | FILE *tmp = fopen("tmp.txt", "w"); |
| 70 | if (tmp == NULL) { |
| 71 | perror("fopen tmp"); |
| 72 | fclose(in); |
| 73 | usage(); |
| 74 | return 1; |
| 75 | } |
| 76 | |
| 77 | int line_ending_style = detect_line_ending(in); |
| 78 | rewind(in); |
| 79 | |
| 80 | if (line_ending_style == 0) { |
| 81 | amiga_to_dos(in, tmp); |
| 82 | } else { |
| 83 | dos_to_amiga(in, tmp); |
| 84 | } |
| 85 | |
| 86 | fclose(in); |
| 87 | fclose(tmp); |
| 88 | |
| 89 | if (remove(argv[1]) != 0) { |
| 90 | perror("元のファイルの削除"); |
| 91 | usage(); |
| 92 | return 1; |
| 93 | } |
| 94 | |
| 95 | if (rename("tmp.txt", argv[1]) != 0) { |
| 96 | perror("tmpファイル名の変更"); |
| 97 | usage(); |
| 98 | return 1; |
| 99 | } |
| 100 | |
| 101 | return 0; |
| 102 | } |