Hello, I have this program I stuck with, I have no idea about it and I need help
ID: 3656585 • Letter: H
Question
Hello, I have this program I stuck with, I have no idea about it and I need help with it You are to write a program that will read numbers from a text file. You will read all of the numbers in the file counting the number of numbers in the file, and accumulating the total of numbers read in. When all numbers have been read in, calculate the average number read in. Note: Your program will not know how many numbers are in the file, so you will read until you get an empty line (which shouldnExplanation / Answer
#include #include #include struct tree { int num, cnt; struct tree *left, *right; }; struct tree *add(struct tree *t, int val) { if (!t) { if (!(t = malloc(sizeof(struct tree)))) perror("Not enough memory"), exit(-1); memset(t, 0, sizeof(struct tree)); t->num = val; ++t->cnt; return t; } if (val num) t->left = add(t->left, val); else if (val > t->num) t->right = add(t->right, val); else ++t->cnt; return t; } int walk(struct tree *t, int (*f)(struct tree *, void*), void *data) { int rc; if (!t) return 0; rc = walk(t->left, f, data); rc += f(t, data); rc += walk(t->right, f, data); return rc; } struct tree *clean(struct tree *t) { if (!t) return NULL; t->left = clean(t->left); t->right = clean(t->right); free(t); return NULL; } int save(struct tree *t, void *data) { int i, rc = 0; FILE *fp = (FILE *) data; for (i = 0; i cnt; ++i) rc += (fprintf(fp, "%d ", t->num) < 0); return rc; } int saveb(struct tree *t, void *data) { int i, rc = 0; FILE *fp = (FILE *) data; for (i = 0; i cnt; ++i) rc += (fwrite((void *) &t->num, sizeof t->num, 1, fp) != 1); return rc; } int main(int argc, char **argv) { int rc = 0; struct tree *t = NULL; char buff[0x200]; FILE *fin, *fout, *foutb; if (argc < 4) { fprintf(stderr, "Usage: %s SRCFILE OUTFILE.TXT OUTFILE.BIN ", argv[0]); exit(0); } if (!((fin = fopen(argv[1], "r")) && (fout = fopen(argv[2], "w")) && (foutb = fopen(argv[3], "wb")))) { perror("fopen"); exit(-1); } while (fgets(buff, sizeof buff, fin)) t = add(t, atoi(buff)); rc += walk(t, save, (void *) fout); rc += walk(t, saveb, (void *) foutb); t = clean(t); fclose(fin); fclose(fout); fclose(foutb); return rc; }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.