/********************************************** Demo Two - Use C to read and write files Steve Dannelly January 2011 The format for the input file must be firstname lastname mm/dd/yyyy The program converts all dates to Julian (days since 4713BC) in order to compute days between two dates. *********************************************/ #include #include #include #include /******************************************************/ // Convert a Gregorian date to Julian date // formula from http://en.wikipedia.org/wiki/Julian_day int convert_to_JDN(int month, int day, int year) { int JDN,a,y,m; a = (14 - month)/12; y = year + 4800 - a; m = month + (12 * a) - 3; JDN = day + ((153*m - 2)/5) + (365*y) + (y/4) + (y/100) + (y/400) - 32045; return JDN; } /******************************************************/ // get today's Julian date int todays_Julian() { int month,day,year; // today's date struct tm *time_info; // parts of today's date // get today's date from the system time_t current = time(0); time_info = localtime (¤t); // correct offsets year = time_info->tm_year + 1900; month = time_info->tm_mon + 1; day = time_info->tm_mday; // convert to a julian number and return that value return convert_to_JDN( month, day, year); } /******************************************************/ /******************************************************/ /******************************************************/ int main () { FILE *infile, *outfile; time_t now; int month, day, year; // data from file char fname[20], lname[20]; // data from file char c1, c2; // skip slashes in dates int birth_JDN, today_JDN, difference; // dates in Julian /***** open input and output files *****/ infile = fopen ("dates.in", "r"); if (infile == NULL) { fprintf(stderr, "Error opening input file\n\n"); exit (1); } outfile = fopen ("dates.out", "w"); if (outfile == NULL) { fprintf(stderr, "Error opening output file\n\n"); exit (1); } // what day is today in Julian? today_JDN = todays_Julian(); // add today's date to top of the output file now = time(0); fprintf (outfile, "As of %s\n", asctime(localtime(&now))); /***** loop through all the dates in the input file ****/ while (fscanf (infile, "%s %s %d %c %d %c %d", fname, lname, &month, &c1, &day, &c2, &year) != -1) { // how long ago was that? birth_JDN = convert_to_JDN (month, day, year); difference = today_JDN - birth_JDN; // write results to outfile fprintf(outfile, "%s %s was born %d days ago,", fname, lname, difference); fprintf(outfile, " or %.3f years\n", difference/365.25); } printf("\nfile succefully converted\n\n"); }