move to using getc

This commit is contained in:
NunoSempere 2023-09-15 11:20:42 +03:00
parent d36eb1e505
commit 59ad6bda13
6 changed files with 14 additions and 14 deletions

Binary file not shown.

View File

@ -3,10 +3,9 @@
int chc(FILE* fp) int chc(FILE* fp)
{ {
char c[1]; register int c;
int num_chars = 0; int num_chars = 0;
int fn = fileno(fp); while ((c = getc(fp)) != EOF) {
while (read(fn, c, sizeof(c)) > 0) {
num_chars ++; num_chars ++;
} }
printf("%i\n", num_chars); printf("%i\n", num_chars);

Binary file not shown.

View File

@ -3,14 +3,14 @@
int lc(FILE* fp) int lc(FILE* fp)
{ {
char c[1];
int num_lines = 0; int num_lines = 0;
int fn = fileno(fp); register int c;
while (read(fn, c, sizeof(c)) > 0) { while ((c = getc(fp)) != EOF) {
if (*c == '\n' ) { if (c == '\n' ) {
num_lines ++; 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); printf("%i\n", num_lines);
return 0; return 0;
} }

BIN
src/wc

Binary file not shown.

View File

@ -3,13 +3,10 @@
int wc(FILE* fp) int wc(FILE* fp)
{ {
char c[1]; register int c;
int word = 0, num_words = 0; int word = 0, num_words = 0;
int fn = fileno(fp); while ((c = getc(fp)) != EOF) {
while (read(fn, c, sizeof(c)) > 0) { if (c != ' ' && c != '\n' && c != '\t') {
// could add error checking to that read call
// could also use getc or fgetc instead of read.
if (*c != ' ' && *c != '\n' && *c != '\t') {
word = 1; word = 1;
} else { } else {
if (word) { if (word) {
@ -33,7 +30,11 @@ int main(int argc, char** argv)
perror("Could not open file"); perror("Could not open file");
return 1; 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 { } else {
printf("Usage: wc file.txt\n"); printf("Usage: wc file.txt\n");
printf(" or: cat file.txt | wc\n"); printf(" or: cat file.txt | wc\n");