#include #include /** * G Towell * created: Sept 2019 * Desc: * File reading in a couple of ways **/ /** * Read a file char by char and store it in a character array * When read complete (or array full) put on a null terminator. * Then print **/ int v1(char * filename) { printf("V1\n"); char holder[256]; FILE *f = fopen(filename, "r"); if (f==NULL) { printf("Cannot open file %s\n", filename); return -1; } int i=0; char c; while (i<255 && EOF!=(c=fgetc(f))) { holder[i++]=c; } holder[i]='\0'; printf("%s\n", holder); return 1; } /** * Slightly more compact that v1, but otherwise the same **/ int v2(char *filename) { char holder[256]; FILE *f = fopen(filename, "r"); if (f==NULL) { printf("Cannot open file %s\n", filename); return -1; } int i=0; while (i<255 && EOF!=(holder[i++]=fgetc(f))) { } if (holder[i-1]==EOF) { i--; } holder[i]='\0'; printf("%s\n", holder); return 1; } /*** * Doing it with pointers rather than array calc **/ int v3(char *filename) { int mx=256; char holder[mx]; FILE *f = fopen(filename, "r"); if (f==NULL) { printf("Cannot open file %s\n", filename); return -1; } int i=0; char * p; p = holder; while (i<(mx-1) && EOF!=(*(p++)=fgetc(f))) { i++; } if (i<(mx-1)) { p--; } *p='\0'; printf("%s\n", holder); return 1; } /** * Danger, write off end of character array !!! * because not keep track of number of chars read **/ int v4(char *filename) { int mx=10; char holder[mx]; FILE *f = fopen(filename, "r"); if (f==NULL) { printf("Cannot open file %s\n", filename); return -1; } char * p = holder; while (EOF!=(*(p++)=fgetc(f))); *p='\0'; printf("%s\n", holder); return 1; } /** * differs from v3 only in printing char by char */ int v5(char *filename) { int mx=256; char holder[mx]; FILE *f = fopen(filename, "r"); if (f==NULL) { printf("Cannot open file %s\n", filename); return -1; } int i=0; char * p; p = holder; while (i<(mx-1) && EOF!=(*(p++)=fgetc(f))) { i++; } if (i<(mx-1)) { p--; } *p='\0'; p=holder; while (*p!='\0') { printf("%c", *(p++)); } return 1; } /** * requires 2 command line args * 1: name of file * 2: which processing method **/ int main(int arrgc, char *argv[]) { char * filename = argv[1]; //int which = (int)strtof(argv[2], NULL); int which = argv[2][0]; switch (which) { case '1': v1(filename); break; case '2': v2(filename); break; case '3': v3(filename); break; case '4': v4(filename); break; default: v5(filename); break; } }