/* =========================================== filename: mergesort.c revision: February 22, 2006 1. C Program to sort a data file containing one positive integer on each line. Usage: mergesort [-f foo.txt] where "foo.txt" is a text file with one positive integer on each line. The program will then sort the lines in "foo.txt" and write the output file "new_foo.txt". 2. The command line specification of the input file is optional. The default is "random_ints.txt". So the default output file is "new_random_ints.txt". ========================================== */ #include #include #include #include "combinatorics.h" #define MAX_NO_INTS 2000 #define DEFAULT_NO_INTS 100 int main(int argc, char *argv[]) { int n = DEFAULT_NO_INTS; int i,j,k; int i1,i2, i3; int j1,j2, j3; int no_lines_read = 0; char mychar; errno_t err; int *s; int *temp_s; char input_filename[100]="random_ints.txt"; char output_filename[100] = "new_"; FILE *input_file; FILE *output_file; // Open file for reading for (i = 1; i < argc; i++) { if (argv[i][0]== '-') { mychar = argv[i][1]; switch (mychar) { case 'n': n = atoi(argv[i+1]); if (n > MAX_NO_INTS) { printf("\nNumber of points is greater than "); printf("%d. Exiting.\n",MAX_NO_INTS); exit(1); } break; case 'f': err = strncpy_s(input_filename,100,argv[i+1],100); break; default: printf("Unrecognized command line option: -%c.\n", mychar); printf("Usage: %s [-n filename]\n",argv[0]); exit(1); break; } } } err = strcat_s(output_filename,100,input_filename); if ((err = fopen_s(&input_file, input_filename, "r" )) !=0 ) { printf("\nThe input file %s was not opened. Exiting.\n",input_filename); exit(1); } if ((err = fopen_s(&output_file, output_filename, "w" )) !=0 ) { printf("\nThe output file %s was not opened. Exiting.\n",output_filename); exit(1); } s = (int *)malloc((n+5)*sizeof(int)); if (s == NULL) { printf("\nUnable to allocate memory for sequence s.\n"); exit(1); } j1 = 0; while(!feof(input_file)) { fscanf_s(input_file, "%d\n", &s[j1]); j1++; } j1--; sort_segment(s,0,j1); for (j2 = 0; j2 <= j1; j2++) { fprintf(output_file, "%d\n", s[j2]); } if (fclose(input_file) != 0) { printf("\nError closing input file. Exiting.\n"); exit(1); } if (fclose(output_file) != 0) { printf("\nError closing output file. Exiting.\n"); exit(1); } else { printf("\nThe input file \"%s\" was successfully closed.\n", input_filename); printf("\nThe output file \"%s\" was successfully\n", output_filename); printf("written and closed.\n"); } free(s); return(0); }