#include #include #include #define SIZE 200 // -------------------------------------------------- void read1(char *filename) { FILE *ptr; // Open a file for reading and check if operation succeeded if ( ( ptr = fopen(filename,"r")) == NULL ) { fprintf(stderr,"File %s could not be opened\n", filename); exit(1); } else { // As long as we didn't reach the end of the file while (!feof(ptr)) { char name[SIZE]; float price; char available; int stock; // Approach 1: we know what to expect, so we can // read the correct types directly if ( fscanf(ptr,"%s %f %c %d\n", name, &price, &available, &stock) == 4 ) { printf("Method1: %s %f %c %d\n", name, price, available, stock); } } } fclose(ptr); } // -------------------------------------------------- void read2(char *filename) { FILE *ptr; // Open a file for reading and check if operation succeeded if ( ( ptr = fopen(filename,"r")) == NULL ) { fprintf(stderr,"File %s could not be opened\n", filename); exit(1); } else { // As long as we didn't reach the end of the file while (!feof(ptr)) { // Approach 2: we can read whole line at once char line[SIZE]; if ( fgets(line, SIZE, ptr) ) { printf("Method2: %s",line); } } } fclose(ptr); } // -------------------------------------------------- int main(int argc, char* argv[]) { if ( argc < 2 ) { fprintf(stderr,"Please enter file name\n"); return 1; } char *input_file = argv[1]; read1(input_file); printf("\n"); read2(input_file); return 0; }