database - How to open a file with a user inputted variable in C? -
i'm writing pos program school assignment. i'm using multiple txt files database. program suppose allow user enter sku number (e.g. 123) open txt file in database (e.g. database/123.txt). pull info txt file such price , allow user add multiple files , end total. user can add database creating new skus. able view transaction history. issue having can't seem figure out how record number user , use number open text file beginning number. (e.g. use enters 123 123.txt opened.)
here section of code need with:
// function start transaction int transaction(void) { // define variables char buf[1000], ndatabase[100]; float nprice[500], ntotal; // instructions printf("you have started transaction.\n"); printf("enter sku number below.\n"); printf("enter 0 complete transaction.\n"); // begin loop here { file *ptr_file; // record sku number /*remove test tools later*/ printf("we r here\n"); scanf("enter sku: %c\n", &ndatabase); printf("now r here\n"); // open database file /*change location later*/ ptr_file = fopen("database/123.txt", "r"); // if file not found return 1 if (!ptr_file) { printf("could not match sku number.\n"); return 1; } while (fgets(buf, 1000, ptr_file) != null) printf("%s\n", buf); scanf("%s", &nprice[0]); // close file fclose(ptr_file); while (ndatabase == 0); ntotal = nprice[0] + nprice[1]; printf("your total is: $%.2f\n", &ntotal); return 0; } }
printf( "enter sku: " ) ; // <-- scanf if input, prompt must output separately scanf( "%s\n", ndatabase); // ^ ^ // | |_no & here - ndatabase array // | // |_accept string not character then might form complete file name sprintf, e.g.
char filename[max_fname] ; sprintf( filename, "database/%s,txt", ndatabase ) ; be aware no error checking or overrun protection performed above - may want consider adding some.
Comments
Post a Comment