update for HEAD-2003050101
[reactos.git] / tools / rline.c
1 /*
2  * Copy a text file with end-of-line character transformation (EOL)
3  *
4  * Usage: rline input-file output-file
5  */
6 #include <sys/stat.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdlib.h>
10
11 char* convert_path(char* origpath)
12 {
13    char* newpath;
14    int i;
15    
16    newpath = strdup(origpath);
17    
18    i = 0;
19    while (newpath[i] != 0)
20      {
21 #ifdef UNIX_PATHS
22         if (newpath[i] == '\\')
23           {
24              newpath[i] = '/';
25           }
26 #else
27 #ifdef DOS_PATHS
28         if (newpath[i] == '/')
29           {
30              newpath[i] = '\\';
31           }
32 #endif  
33 #endif  
34         i++;
35      }
36    return(newpath);
37 }
38
39 int
40 fsize (FILE * f)
41 {
42   struct stat st;
43   int fh = fileno (f);
44    
45   if (fh < 0 || fstat (fh, &st) < 0)
46     return -1;
47   return (int) st.st_size;
48 }
49
50 int main(int argc, char* argv[])
51 {
52   char* path1;
53   char* path2;
54   FILE* in;
55   FILE* out;
56   char* in_buf;
57   char* out_buf;
58   int in_size;
59   int in_ptr;
60   int linelen;
61   int n_in;
62   int n_out;
63   char eol_buf[2];
64
65   /* Terminate the line with windows EOL characters (CRLF) */
66   eol_buf[0] = '\r';
67   eol_buf[1] = '\n';
68
69    if (argc != 3)
70      {
71         fprintf(stderr, "Wrong argument count\n");
72         exit(1);
73      }
74    
75    path1 = convert_path(argv[1]);
76    path2 = convert_path(argv[2]);
77    
78    in = fopen(path1, "rb");
79    if (in == NULL)
80      {
81         perror("Cannot open input file");
82         exit(1);
83      }
84
85   in_size = fsize(in);
86   in_buf = malloc(in_size);
87   if (in_buf == NULL)
88     {
89           perror("Not enough free memory");
90           fclose(in);
91           exit(1);
92     }
93
94    out = fopen(path2, "wb");
95    if (out == NULL)
96      {
97         perror("Cannot open output file");
98         fclose(in);
99         exit(1);
100      }
101
102   /* Read it all in */
103   n_in = fread(in_buf, 1, in_size, in);
104
105   in_ptr = 0;
106   while (in_ptr < in_size)
107     {
108       linelen = 0;
109
110       while ((in_ptr + linelen < in_size) && (in_buf[in_ptr + linelen] != '\r') && (in_buf[in_ptr + linelen] != '\n'))
111         {
112           linelen++;
113         }
114       if (linelen > 0)
115         {
116           n_out = fwrite(&in_buf[in_ptr], 1, linelen, out);
117           in_ptr += linelen;
118         }
119       /* Terminate the line  */
120       n_out = fwrite(&eol_buf[0], 1, sizeof(eol_buf), out);
121
122       if ((in_ptr < in_size) && (in_buf[in_ptr] == '\r'))
123         {
124           in_ptr++;
125         }
126
127       if ((in_ptr < in_size) && (in_buf[in_ptr] == '\n'))
128         {
129           in_ptr++;
130         }
131     }
132
133   free(in_buf);
134   fclose(in);
135
136   exit(0);
137 }