-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.c
108 lines (85 loc) · 2.98 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* ===========================================================
* Name:
* Section:
* Project: Practice debugging lab.
* ===========================================================
*/
/****************************************************************
* COMPLETION INSTRUCTIONS:
*
* This program should read numbers from a file and store them in an array.
*
* The program should then (based on the user's selection) check to see
* if the values are stored in ascending or descending order.
*
* There are errors present in this code you should fix them.
****************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_NUMBERS 1000 /* Max numbers in file */
char* DATA_FILE = ""; /* The name of the data file (will be filled in by user) */
int data[MAX_NUMBERS]; /* Array of numbers to search */
int max_count; /* Number of valid elements in data */
int main(int argc, char** argv) {
FILE *in_file; /* Input file */
int i; /* Keeps track of where we are in the array*/
int prev; /* the previous number */
int max; /* maxinimum value found*/
int min; /* minimum value found*/
int mode; /* 1 = ascending; 2 = descending */
char line[80]; /* Input line */
printf("What is the name of the file: ");
fgets(DATA_FILE, 100, stdin);
DATA_FILE[strlen(DATA_FILE)] = '\0';
in_file = fopen(DATA_FILE, "r");
if (in_file == NULL) {
fprintf(stderr, "Error:Unable to open %s\n", DATA_FILE);
exit(8);
}
/*
* Read in data
*/
max_count = 0;
while (1) {
// Tests to see if the end of the file has been reached
if (fgets(line, sizeof(line), in_file) == NULL)
break;
/* convert number */
sscanf(line, "%d", data[max_count])
max_count++;
}
printf("Enter 1 to check %s for ascending order; 2 for descending; -1 to exit: ", DATA_FILE);
scanf("%d", &mode);
if (mode == -1)
return 0;
prev = data[0];
i = 0;
while (1) {
if (i == max_count && mode == 1) {
printf("File is sorted in ascending order (min = %d; max = %d)\n", min, max);
break;
}
if (i == max_count && mode == 2) {
printf("File is sorted in descending order (max = %d; min = %d)\n", min, max);
break;
}
if (mode == 1 && data[i] > prev) {
printf("Not in ascending order as of index %d. Terminating.\n", i);
break;
}
if (mode == 2 && data[i] < prev) {
printf("Not in ascending order as of index %d. Terminating.\n", i);
break;
}
if (data[i] > max) {
max = data[i];
}
if (data[i] < min) {
min = data[i];
}
++i;
}
return 0;
}