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