c - Reading and printing to/from a file -
i taking course of study on c , have been faced next task: 1. load xcode , start new c project. if wish, remove extraneous code project left what’s necessary run main function in project. 2. prompt user come in 2 values-- first char value of ‘d’ or ‘c’. sec value should floating point value representing amount of money. 3. each value entered record text file saves in next format: d, 250\n c, 500\n 4. test programme , examine text file creates insure in required format. 5. write sec programme assumes starting balance of $1,000.00 , outputs completed ledger , final balance account, adding or subtracting each entry text file created. entries marked ‘c’ should added business relationship , entries marked ‘d’ should debited (subtracted).
i have created file , onto step 5, believe know how obtain first character file check if 'c' or 'd', after not sure how obtain numerical value same line. how do this? code far(i unsure set in if/else if statements):
file *pfile = fopen("users/justin/desktop/ledger.txt", "r"); float startingbalance = 1000.00; char action; if(pfile != null) { while(!(feof(pfile))) { fgets(action, 1, pfile); if(action == 'd' || action == 'd') { } else if(action == 'c' || action == 'c') { } else printf("io error: problem file"); } } homecoming 0; }
your file organised in lines, it's best read line-wise. function fgets
, read whole line of maximum length char buffer. keeps terminating newline (unless line truncated because of max length, let's not deal right now). fgets
returns line buffer or null
if end of file reached.
once have line, must examine line. lines have same syntax, namely
<action>, <amount>
so utilize sscanf
, isn't nice quick , dirty. (scanf
s error handling, example, basic, strategy ignore badly formatted lines altogether.)
the skeleton of function might this:
int ledger(const char *fn) { file *f; char line[80]; /* char buffer line */ int lineno = 0; /* error reporting */ f = fopen(fn, "r"); if (f == null) homecoming -1; /* error */ while (fgets(line, sizeof(line), f)) { char action; double amount; int n; lineno++; n = sscanf(line, " %c, %lf", &action, &amount); if (n < 2) { printf("skipping badly formatted line %d\n", lineno); continue; } /* stuff, e.g. print */ printf("%c, %16.2f\n", action, amount); } fclose(f); homecoming 0; /* success */ }
c file fgets
No comments:
Post a Comment