3 /* must be defined before */
5 #define _CRT_SECURE_NO_DEPRECATE
19 #define _CRT_SECURE_NO_DEPRECATE
20 #define strdup _strdup
21 #define fileno _fileno
30 #define max(h,i) ((h) > (i) ? (h) : (i))
34 #define S_ISREG(__mode) (((__mode) & S_IFMT) == S_IFREG)
38 #define STDIN_FILENO 0
42 #define STDOUT_FILENO 1
47 int exit_code = EXIT_SUCCESS;
72 cat_files(char** fnames);
87 for(i = 0; i < fnumber; i++)
104 main(int argc, char *argv[])
111 struct stat stat_buf = {0};
113 setlocale(LC_ALL, "");
117 if(!(buf = (char*)malloc(bsize)))
119 fprintf(stderr, "[ERROR/cat] not enough memory\n");
125 if(!(fnames = (char**)calloc(argc, sizeof(char*))))
127 fprintf(stderr, "[ERROR/cat] not enough memory\n");
131 for(i = 1, j= 0; i < argc; i++)
133 if(!strcmp(argv[i], ">"))
138 else if(!strcmp(argv[i], ">>"))
146 if(stat(argv[i], &stat_buf))
148 fprintf(stderr, "[ERROR/cat (1)] could not get information about %s\n",argv[i]);
154 if(S_ISREG(stat_buf.st_mode))
156 fnames[j++] = strdup(argv[i]);
161 fprintf(stderr, "[ERROR/cat] %s is not a file\n",argv[i]);
178 fprintf(stderr, "[ERROR/cat] syntax error near `>>' (i : %d - argc : %d\n", i , argc);
180 fprintf(stderr, "[ERROR/cat] syntax error near `>' (i : %d - argc : %d\n", i , argc);
186 wfname = strdup(argv[i + 1]);
190 if((wfd = creat(wfname, _S_IREAD | _S_IWRITE)) < 0)
192 fprintf(stderr, "[ERROR/cat] could not create %s file\n",wfname);
199 if((wfd = open(wfname, O_WRONLY | O_APPEND, 0)) < 0)
201 fprintf(stderr, "[ERROR/cat] could not open %s file\n",wfname);
212 if(fstat(wfd, &stat_buf))
214 fprintf(stderr, "[ERROR/cat (3)] could not get information about stdout\n");
219 exit_code = cat_files(fnames);
221 if(wfd == STDOUT_FILENO)
225 fprintf(stderr, "[ERROR/cat] could not close stdout\n");
226 exit_code = EXIT_FAILURE;
233 fprintf(stderr, "[ERROR/cat] could not close %s\n", wfname);
234 exit_code = EXIT_FAILURE;
242 cat_files(char **fnames)
254 for(i = 0; i < fnumber && !failure; i++)
256 if (!strcmp(fnames[i], "-"))
258 else if ((rfd = open(fnames[i], O_RDONLY, 0)) < 0)
260 fprintf(stderr, "[WARN/cat] could not open %s file", fnames[i]);
261 exit_code = EXIT_FAILURE;
276 return failure ? 1 : 0;
284 size_t bytes_readed_nb;
288 int bytes_written_nb, pos;
290 while ((bytes_readed_nb = read(rfd, buf, bsize)) != -1 && bytes_readed_nb != 0)
292 for (pos = 0; bytes_readed_nb; bytes_readed_nb -= bytes_written_nb, pos += bytes_written_nb)
294 if ((bytes_written_nb = write(wfd, buf + pos, bytes_readed_nb)) == 0 || bytes_written_nb == -1)
296 fprintf(stderr, "[ERROR/cat] could not write to %s\n", wfd == fileno(stdout) ? "stdout" : wfname);
302 if(bytes_readed_nb < 0)
304 fprintf(stderr, "[WARN/cat] could not read %s file", rfname);