scores/top.c (view raw)
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 |
#include <stdio.h>
#include <stdlib.h>
int read_input(char **bufferptr) {
FILE *fptr;
fptr = fopen("scores.txt", "r");
if (fptr == NULL) {
printf("ERROR: can't open file");
return 0;
}
fseek(fptr, 0L, SEEK_END);
size_t sz = ftell(fptr);
rewind(fptr);
*bufferptr = malloc(sz + 1);
if (*bufferptr == NULL) {
fclose(fptr);
printf("ERROR: couldn't allocate memory");
return 0;
}
size_t bytes_read = fread(*bufferptr, 1, sz, fptr);
(*bufferptr)[bytes_read] = '\0';
fclose(fptr);
return sz;
}
int total_score = 0;
void pp(int position, int score) {
printf("Die Top %d haben %d gezählt und machen damit %f%% aus.\n", position,
score, (float)score / (float)total_score * 100);
}
int main() {
char *buffer = NULL;
int sz = read_input(&buffer);
if (!sz)
return 1;
int i = -1, buf2i = -1;
char *buffer2 = malloc(sz);
// read total score
while (1) {
i++, buf2i++;
if (buffer[i] == '\n') {
buffer2[buf2i] = '\0';
total_score = atoi(buffer2);
break;
}
buffer2[buf2i] = buffer[i];
}
buf2i = -1;
int position = 0, score = 0;
// read other values
while (1) {
i++, buf2i++;
if (i == sz)
break;
if (buffer[i] == '\n') {
buffer2[buf2i] = '\0';
score += atoi(buffer2);
buf2i = -1;
position++;
if (position == 1 || position == 3 || position == 5 || position == 10)
pp(position, score);
continue;
}
buffer2[buf2i] = buffer[i];
}
}
|