static char *usage = "usage: %s <N> <filename>\n";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* #define DEBUG */
#if defined(DEBUG)
#include "xmalloc.h"
#else
#define xmalloc(x, y) malloc(x)
#define xfree(x, y) free(x)
#define xrealloc(x, y, z) realloc((x), (y))
#define xmallocdump()
#endif
#define GETLINE 1001
#define IDARRAY 1002
#define IDNAME 1003
#define BUFFSIZE 3 /* >= 2 */
char *mygetline(FILE *fp) {
static char inbuff[BUFFSIZE];
char *outbuff_malloc, *tmpbuff;
char *p, *r;
int fEOL;
if ((outbuff_malloc = xmalloc(1, GETLINE)) == NULL) {
return NULL;
}
*outbuff_malloc = '\0';
fEOL = 0;
do {
r = fgets(inbuff, BUFFSIZE, fp);
if (r == NULL)
break;
for (p = inbuff; *p != '\0'; p++)
;
if (*(p - 1) == '\n')
fEOL = 1;
if ((tmpbuff = xrealloc(outbuff_malloc,
strlen(outbuff_malloc) + strlen(inbuff) + 1,
GETLINE)) == NULL) {
xfree(outbuff_malloc, GETLINE);
return NULL;
}
strcat(tmpbuff, inbuff);
outbuff_malloc = tmpbuff;
} while (!fEOL);
if (strlen(outbuff_malloc) > 0) {
for (p = outbuff_malloc; *p != '\0'; p++)
;
if (*(p - 1) == '\n')
*(p - 1) = '\0';
return outbuff_malloc;
}
xfree(outbuff_malloc, GETLINE);
return NULL;
}
void task_console2file(int n, char *filename) {
FILE *fp;
int i;
if ((fp = fopen(filename, "w")) == NULL)
return;
for (i = 0; i < n; i++) {
int no;
char *p;
do {
printf("No: ");
} while ((p = mygetline(stdin)) == NULL);
no = atoi(p);
xfree(p, GETLINE);
do {
printf("Name: ");
} while ((p = mygetline(stdin)) == NULL);
fprintf(fp, "%d, %s\n", no, p);
xfree(p, GETLINE);
}
fclose(fp);
}
struct stu {
int num;
char *name;
};
int cmp(struct stu *a, struct stu *b) {
return a->num > b->num;
}
void task_readfile_sort(int n, char *filename) {
FILE *fp;
struct stu *a;
int i, max;
if ((fp = fopen(filename, "r")) == NULL)
return;
if ((a = xmalloc(sizeof(struct stu) * n, IDARRAY)) == NULL)
return;
for (i = 0; i < n; i++) {
char *p, *q;
if ((p = mygetline(fp)) == NULL)
break;
for (q = p; *q != ','; q++)
;
*q = '\0';
q++;
a[i].num = atoi(p);
if ((a[i].name = xmalloc(strlen(q) + 1, IDNAME)) == NULL) {
xfree(p, GETLINE);
break;
}
strcpy(a[i].name, q);
xfree(p, GETLINE);
}
fclose(fp);
max = i;
qsort(a, max, sizeof(a[0]), (int (*)(const void *, const void *))cmp);
for (i = 0; i < max; i++)
printf("%d: %s\n", a[i].num, a[i].name);
for (i = 0; i < max; i++)
xfree(a[i].name, IDNAME);
xfree(a, IDARRAY);
}
int main(int argc, char *argv[]) {
FILE *fp;
int n;
if (argc != 3) {
fprintf(stderr, usage, argv[0]);
exit(-1);
}
n = atoi(argv[1]);
if (n <= 0) {
fprintf(stderr, "n must be > 0\n");
fprintf(stderr, usage, argv[0]);
exit(-1);
}
if ((fp = fopen(argv[2], "w")) == NULL) {
fprintf(stderr, "cannot open the file: %s\n", argv[2]);
fprintf(stderr, usage, argv[0]);
exit(-1);
}
fclose(fp);
task_console2file(n, argv[2]);
task_readfile_sort(n, argv[2]);
xmallocdump();
return 0;
}
/* end */