/* BEGIN file_mul.c */ /* From news:comp.lang.c > I want to read integers from a text file and > want to do some operation in the main program. > To be more specific I need to multiply each of these integers > with another set of integers stored in an array. */ #include "file_lib.h" #include "list_lib.h" #include #include #define INTEGERS 17 #define LU_RAND_SEED 123456789LU #define LU_RAND(S) ((S) * 69069LU + 362437 & 0XFFFFFFFF) #define NMEMB(A) (sizeof (A) / sizeof *(A)) int main(void) { int rc; size_t index; FILE *fp; char fn[L_tmpnam]; long unsigned array[INTEGERS]; long unsigned seed = LU_RAND_SEED; size_t size = 0; char *buff = NULL; list_type *head = NULL; list_type *tail = NULL; puts("/* BEGIN file_mul.c output */\n"); tmpnam(fn); fp = fopen(fn, "w"); if (fp == NULL) { fputs("fopen(fn), \"w\") == NULL\n", stderr); exit(EXIT_FAILURE); } puts("File open for writing."); puts("File values:"); for (index = 0; index != NMEMB(array); ++index) { seed = LU_RAND(seed); fprintf( fp, "%lu\n", seed & 0xff); fprintf(stdout, "%4lu" , seed & 0xff); seed = LU_RAND(seed); array[index] = seed & 0x3; } putchar('\n'); fclose(fp); puts("File closed."); puts("Array values:"); for (index = 0; index != NMEMB(array); ++index) { fprintf(stdout, "%4lu", array[index]); } putchar('\n'); fp = fopen(fn, "r"); if (fp == NULL) { fputs("fopen(fn, \"r\") == NULL\n", stderr); exit(EXIT_FAILURE); } puts("File open for reading."); puts("Reading file into a linked list..."); while ((rc = get_line(&buff, &size, fp)) > 0) { tail = list_append(&head, tail, buff, rc); if (tail == NULL) { fputs("tail == NULL\n", stderr); break; } } fclose(fp); puts("File closed."); fp = fopen(fn, "w"); if (fp == NULL) { fputs("fopen(fn), \"w\") == NULL\n", stderr); exit(EXIT_FAILURE); } puts("File open for writing."); puts("Writing file with products of list and array values..."); tail = head; index = 0; while (index != NMEMB(array) && tail != NULL) { seed = strtoul(tail -> data, NULL, 10); tail = tail -> next; fprintf(fp, "%lu\n", array[index] * seed); ++index; } list_free(head, free); puts("List is freed."); fclose(fp); puts("File closed."); fp = fopen(fn, "r"); if (fp == NULL) { fputs("fopen(fn, \"r\") == NULL\n", stderr); exit(EXIT_FAILURE); } puts("File open for reading."); puts("File values:"); while ((rc = get_line(&buff, &size, fp)) > 0) { fprintf(stdout, "%4s", buff); } putchar('\n'); free(buff); puts("Line reading buffer is freed."); fclose(fp); puts("File closed."); remove(fn); puts("File removed."); puts("\n/* END file_mul.c output */"); return 0; } /* END file_mul.c */