Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <getopt.h>
- #include "s21_cat.h"
- int main(int argc, char* argv[]) {
- const char* short_opt = "benstvTE";
- const struct option long_opt[] = {
- {"number-nonblank", no_argument, NULL, 'b'},
- {"number", no_argument, NULL, 'n'},
- {"squeeze-blank", no_argument, NULL, 's'},
- {NULL, 0, NULL, 0}
- };
- int index_opt = -1;
- int error = 0;
- struct opts cat_opt = {0, 0, 0, 0, 0, 0};
- for (int opt; (opt = getopt_long(argc, argv, short_opt, long_opt, &index_opt)) != -1;) {
- // printf("opt: %c\n", opt);
- switch (opt) {
- case 'b':
- cat_opt.b = 1;
- break;
- case 'e':
- case 'E':
- cat_opt.e = 1;
- cat_opt.v = 1;
- break;
- case 'n':
- cat_opt.n = 1;
- break;
- case 's':
- cat_opt.s = 1;
- break;
- case 't':
- case 'T':
- cat_opt.t = 1;
- cat_opt.v = 1;
- break;
- case 'v':
- cat_opt.v = 1;
- break;
- case '?':
- fprintf(stderr, "usage: cat [options] [file ...]\n");
- error = 1;
- break;
- }
- }
- if (!error) {
- // printf("-b: %d\n", cat_opt.b);
- // printf("-e: %d\n", cat_opt.e);
- // printf("-n: %d\n", cat_opt.n);
- // printf("-s: %d\n", cat_opt.s);
- // printf("-t: %d\n", cat_opt.t);
- for (int index = optind; index < argc; index++) {
- // printf ("Non-option argument %s\n", argv[index]);
- if (output(argv[index], cat_opt)) {
- fprintf(stderr, "%s: %s: %s\n", CAT, argv[index], strerror(errno));
- error = 1;
- }
- }
- }
- return error;
- }
- int output(const char* cat_file, struct opts cat_opt) {
- int error = 0;
- int ch;
- FILE* fp;
- fp = fopen(cat_file, "rt");
- if (fp && (ch = getc(fp)) != -1) {
- #if defined(__APPLE__)
- size_t num = 1;
- #else
- static size_t num = 1;
- #endif
- int new_line = 1;
- int exclude_line = 0;
- while (!feof(fp) && !ferror(fp)) {
- if (ch != EOF) {
- if ((cat_opt.b && new_line && ch !='\n') || (cat_opt.n && new_line && !cat_opt.b)) {
- printf("%*zu\t", WIDTH, num);
- num++;
- new_line = 0;
- }
- if (ch == '\n') {
- new_line = 1;
- if (cat_opt.e && exclude_line < 2) {
- printf("$");
- }
- if (cat_opt.s) {
- exclude_line++;
- }
- } else {
- exclude_line = 0;
- }
- if (exclude_line > 2) {
- exclude_line = 0;
- } else {
- if (cat_opt.v) {
- if (ch < 9 || (ch > 10 && ch < 32)) {
- printf("^%c", ch + 64);
- } else if (cat_opt.t && ch == '\t') {
- printf("^I");
- } else if (ch == 127) {
- printf("^?");
- } else if (ch > 127 && ch < 160) {
- printf("M-^%c", ch - 64);
- #if defined(__linux__)
- } else if (ch > 159 && ch < 255) {
- printf("M-%c", ch - 128);
- } else if (ch == 255) {
- printf("M-^?");
- #endif
- } else {
- putchar(ch);
- }
- } else {
- putchar(ch);
- }
- }
- ch = getc(fp);
- }
- }
- fclose(fp);
- } else {
- error = 1;
- }
- return error;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement