summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJosias <justjosias@tutanota.com>2020-04-22 15:45:58 +0300
committerJosias <justjosias@tutanota.com>2020-04-22 15:45:58 +0300
commit3326cf6334eebb7fd1e871148aaf8bdbf1710a0d (patch)
tree3fe56db591f25de9901335af16a2b1f557dab185
parentf79b58016e1757164e5e3f3e4d7a0b9533981e8d (diff)
Improve documentation and add omitted code
-rw-r--r--rccat.c14
-rw-r--r--rccat.md14
2 files changed, 20 insertions, 8 deletions
diff --git a/rccat.c b/rccat.c
index 2963758..73b718d 100644
--- a/rccat.c
+++ b/rccat.c
@@ -21,7 +21,7 @@ void printColors(char *text)
if (!(isatty(STDOUT_FILENO))) {
printf("%s", text);
return;
- }
+ }
if (text) {
for (int i = 0; i < strlen(text); ++i) {
int color = 0;
@@ -32,16 +32,19 @@ void printColors(char *text)
printf("%s%c", colors[color], text[i]);
}
}
- printf("%s", KWHT);
+ printf("%s", KWHT);
}
int main(int argc, char *argv[])
{
srand(time(NULL));
char buffer[BUF_SIZE] = {""};
-
+
for (int i = 0; i < argc; ++i) {
if (strcmp(argv[i], "-") == 0 || argc == 1) {
-
+ while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
+ printColors(buffer);
+ }
+ clearerr(stdin);
} else if (i >= 1) {
FILE *fp;
fp = fopen(argv[i], "r");
@@ -53,12 +56,11 @@ int main(int argc, char *argv[])
buffer[got] = '\0';
printColors(buffer);
}
- printf("%s", KWHT);
if (ferror(fp))
fprintf(stderr, "Error: can't read %s\n", argv[1]);
fclose(fp);
}
}
-
+
return EXIT_SUCCESS;
}
diff --git a/rccat.md b/rccat.md
index 69520b8..b58243f 100644
--- a/rccat.md
+++ b/rccat.md
@@ -59,7 +59,7 @@ void printColors(char *text)
if (text) {
<<normal>>
}
- <<reset>>
+ <<reset>>
}
```
@@ -122,17 +122,27 @@ if (strcmp(argv[i], "-") == 0 || argc == 1) {
}
```
+
+This reads the file section by section in chucks the size of `BUF_SIZE` and prints them with `printColors`.
+If the section is unreadable, it prints an error to `stdout`.
``` {.c #read-file}
size_t got;
while ((got = fread(buffer, 1, BUF_SIZE -1, fp))) {
buffer[got] = '\0';
printColors(buffer);
}
- printf("%s", KWHT);
if (ferror(fp))
fprintf(stderr, "Error: can't read %s\n", argv[1]);
```
+Basically the same as above, but gets text from `stdin` instead of a file pointer. In addition, it needs to call `clearerr` to be able to reopen the input stream for multiple `-` arguments.
+``` {.c #print-from-stdin}
+while (fgets(buffer, BUF_SIZE, stdin) != NULL) {
+ printColors(buffer);
+}
+clearerr(stdin);
+```
+
Prepare a file pointer and make sure the file exists. If not, write an error to `stderr`.
``` {.c #open-file}
FILE *fp;