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;
51 static char *wfname = NULL;
63 static char *buf = NULL;
68 int cat_files(char **fnames);
74 void exit0(int errcode)
79 for (i = 0; i < fnumber; i++)
95 int main(int argc, char *argv[])
102 struct stat stat_buf = { 0 };
104 setlocale(LC_ALL, "");
108 if (!(buf = (char *) malloc(bsize))) {
109 fprintf(stderr, "[ERROR/cat] not enough memory\n");
114 if (!(fnames = (char **) calloc(argc, sizeof(char *)))) {
115 fprintf(stderr, "[ERROR/cat] not enough memory\n");
119 for (i = 1, j = 0; i < argc; i++) {
120 if (!strcmp(argv[i], ">")) {
123 } else if (!strcmp(argv[i], ">>")) {
128 if (stat(argv[i], &stat_buf)) {
130 "[ERROR/cat (1)] could not get information about %s\n",
135 if (S_ISREG(stat_buf.st_mode)) {
136 fnames[j++] = strdup(argv[i]);
139 fprintf(stderr, "[ERROR/cat] %s is not a file\n", argv[i]);
155 "[ERROR/cat] syntax error near `>>' (i : %d - argc : %d\n",
159 "[ERROR/cat] syntax error near `>' (i : %d - argc : %d\n",
164 wfname = strdup(argv[i + 1]);
167 if ((wfd = creat(wfname, _S_IREAD | _S_IWRITE)) < 0) {
168 fprintf(stderr, "[ERROR/cat] could not create %s file\n",
174 if ((wfd = open(wfname, O_WRONLY | O_APPEND, 0)) < 0) {
175 fprintf(stderr, "[ERROR/cat] could not open %s file\n", wfname);
184 if (fstat(wfd, &stat_buf)) {
186 "[ERROR/cat (3)] could not get information about stdout\n");
191 exit_code = cat_files(fnames);
193 if (wfd == STDOUT_FILENO) {
194 if (fclose(stdout)) {
195 fprintf(stderr, "[ERROR/cat] could not close stdout\n");
196 exit_code = EXIT_FAILURE;
200 fprintf(stderr, "[ERROR/cat] could not close %s\n", wfname);
201 exit_code = EXIT_FAILURE;
208 int cat_files(char **fnames)
219 for (i = 0; i < fnumber && !failure; i++) {
220 if (!strcmp(fnames[i], "-"))
222 else if ((rfd = open(fnames[i], O_RDONLY, 0)) < 0) {
223 fprintf(stderr, "[WARN/cat] could not open %s file", fnames[i]);
224 exit_code = EXIT_FAILURE;
238 return failure ? 1 : 0;
245 size_t bytes_readed_nb;
249 int bytes_written_nb, pos;
251 while ((bytes_readed_nb = read(rfd, buf, bsize)) != -1
252 && bytes_readed_nb != 0) {
253 for (pos = 0; bytes_readed_nb;
254 bytes_readed_nb -= bytes_written_nb, pos += bytes_written_nb) {
255 if ((bytes_written_nb = write(wfd, buf + pos, bytes_readed_nb)) == 0
256 || bytes_written_nb == -1) {
257 fprintf(stderr, "[ERROR/cat] could not write to %s\n",
258 wfd == fileno(stdout) ? "stdout" : wfname);
264 if (bytes_readed_nb < 0) {
265 fprintf(stderr, "[WARN/cat] could not read %s file", rfname);