#include #include #include main() { char relation[32]; /*room for 32-char string*/ char retort[64]; double months, days, years; int assigned; FILE *fp; /* we must deal with files using file pointers */ fp =fopen("data", "r"); /*look for file of that name and open for reading*/ /*returns null pointer and sets error # if fails, (e.g. no file of that name). */ /* below, the space between My and %s means whitespace is skipped */ assigned = fscanf(fp, "My %s is %lf months and %lf days old.", relation, &months, &days); /* (f)scanf returns the number of items successfully assigned (there's an option (involving *) to scan but discard an item, which does not up the assignment count). Here we see the scanner looking for exact matches (e.g for "My"), for %s an arbitrary string, and for %lf, a representation of a long float (with or without signs, decimal points, etc)*/ /*Send (f)scanf the address of variables (as in &months). There's no & for relation since it's an array name and thus IS the address of its first element.*/ printf("\n %d values assigned: months = %f, days= %f, relation = '%s'\n", assigned, months, days, relation); /*did it work?*/ fclose(fp); /*finished reading*/ /* next create new file whose name is the relation */ /* w+ means open or reopen for writing but also allow reading */ fp = fopen(relation, "w+"); years = (30.4 * months + days)/365; /*convert units for fun*/ fprintf(fp, "So your %s is about %f years old.\n", relation, years); /* classic example of formatted print command. */ /* to go to beginning of file use rewind: */ rewind(fp); /* this next is really non-obvious, first time I've used it: [^\n] means take anything but an end of line, and the final \n matches the one I wrote with my fprintf, so the whole line is read in as a string. Rereading documentation is good: useful features keep popping out. */ fscanf(fp, "%[^\n]\n", retort); /*create retort string*/ printf("%s\n\n", retort); fclose(fp); }