suwako / txtconv アーカイブ

このリポジトリはアーカイブされています。読むだけで、プッシュやイシューの変更は出来ません。

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