commit 59ad6bda139a52dbb50d8d29ade08f738ebb7850
parent d36eb1e505728bc043f8504fc6344e499401ab89
Author: NunoSempere <nuno.sempere@protonmail.com>
Date: Fri, 15 Sep 2023 11:20:42 +0300
move to using getc
Diffstat:
6 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/src/extra/chc/chc b/src/extra/chc/chc
Binary files differ.
diff --git a/src/extra/chc/chc.c b/src/extra/chc/chc.c
@@ -3,10 +3,9 @@
int chc(FILE* fp)
{
- char c[1];
+ register int c;
int num_chars = 0;
- int fn = fileno(fp);
- while (read(fn, c, sizeof(c)) > 0) {
+ while ((c = getc(fp)) != EOF) {
num_chars ++;
}
printf("%i\n", num_chars);
diff --git a/src/extra/lc/lc b/src/extra/lc/lc
Binary files differ.
diff --git a/src/extra/lc/lc.c b/src/extra/lc/lc.c
@@ -3,14 +3,14 @@
int lc(FILE* fp)
{
- char c[1];
int num_lines = 0;
- int fn = fileno(fp);
- while (read(fn, c, sizeof(c)) > 0) {
- if (*c == '\n' ) {
+ register int c;
+ while ((c = getc(fp)) != EOF) {
+ if (c == '\n' ) {
num_lines ++;
}
}
+ // num_lines += (c != '\n'); // < judgment call, adds a line if the last line isn't followed by a newline.
printf("%i\n", num_lines);
return 0;
}
diff --git a/src/wc b/src/wc
Binary files differ.
diff --git a/src/wc.c b/src/wc.c
@@ -3,13 +3,10 @@
int wc(FILE* fp)
{
- char c[1];
+ register int c;
int word = 0, num_words = 0;
- int fn = fileno(fp);
- while (read(fn, c, sizeof(c)) > 0) {
- // could add error checking to that read call
- // could also use getc or fgetc instead of read.
- if (*c != ' ' && *c != '\n' && *c != '\t') {
+ while ((c = getc(fp)) != EOF) {
+ if (c != ' ' && c != '\n' && c != '\t') {
word = 1;
} else {
if (word) {
@@ -33,7 +30,11 @@ int main(int argc, char** argv)
perror("Could not open file");
return 1;
}
- return wc(fp) && fclose(fp);
+ int wc_status = wc(fp);
+ int fclose_status = fclose(fp);
+ return (wc_status == 0) && (fclose_status ==0);
+ // can't do return wc_status == 0 && fclose_status == 0;
+ // because then if wc returns with -1, fclose is not called.
} else {
printf("Usage: wc file.txt\n");
printf(" or: cat file.txt | wc\n");