#include #include #include #define FILENAME 20 #define MAXLINE 200 #define DAYLENGTH 4 #define PREFIX "nip" #define SUFFIX ".txt" void reverse(char s[]) { int c, i, j; for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } void itoa (int n, char s[]) { int i = 0; do { s[i++] = n % 10 + '0'; } while ((n /= 10) > 0); s[i] = '\0'; reverse(s); } int getDay(char line[]) { char dayString[DAYLENGTH]; int i, j; i = j = 0; while (!isspace(line[i++])); // move beyond first field while (isspace(line[i++])); // move beyond white space to second field while (!isspace(line[i++])); // move beyond second field while (isspace(line[i++])); // move beyond white space to julian day field that we're after --i; // back up one - when we reached the first no-space, 'i' was still incremented; while (!isspace(line[i])) dayString[j++] = line[i++]; // copy julian day as a string dayString[i] = '\0'; // null terminate return (atoi(dayString)); } void makeFileName(int currentDay, char sepFileName[]) { char dayString[DAYLENGTH]; itoa(currentDay, dayString); strcpy(sepFileName, PREFIX); strcat(sepFileName, dayString); strcat(sepFileName, SUFFIX); } void separate(char fileName[]) { FILE *tempFile, *newFile; char line[MAXLINE], sepFileName[FILENAME]; int currentDay, lineDay; currentDay = lineDay = 0; printf("Separating %s:\n", fileName); tempFile = fopen(fileName, "r"); if (tempFile) { fgets(line, MAXLINE, tempFile); currentDay = getDay(line); makeFileName(currentDay, sepFileName); newFile = fopen(sepFileName, "a"); while (!feof(tempFile)) { lineDay = getDay(line); if (lineDay == currentDay) fputs(line, newFile); else { // reached the next julian day in the file fclose(newFile); // close previous day's file currentDay = lineDay; // set new currentDay makeFileName(currentDay, sepFileName); newFile = fopen(sepFileName, "a"); fputs(line, newFile); } fgets(line, MAXLINE, tempFile); // read in the next line } } else printf("\tCouldn't open %s.\n\n", fileName); } int main() { FILE *fileList; char fileName[FILENAME]; system("ls *.temp > temp_file_list"); fileList = fopen("temp_file_list", "r"); if (fileList) { fscanf(fileList, "%s", fileName); do { separate(fileName); fscanf(fileList, "%s", fileName); } while (!feof(fileList)); } return 0; }