#include
#include
#define ALEN(a) (sizeof(a)/sizeof((a)[0]))
#define NAMELEN 31
typedef struct s_playerinfo{
int playernumber;
char fisrtname[NAMELEN];
char lastname[NAMELEN];
int otab;
int noh;
int walks;
int rbis;
}PLAYERINFO;
typedef int (*GET_FILE_ELEMENT)(FILE *fp, PLAYERINFO *pi);
int skip_file_space(FILE *fp) {
int c;
c = fgetc(fp);
if (c != EOF) {
if (isspace(c)) {
do {
if (!isspace(c)) {
ungetc(c, fp);
break;
}
}while ((c = fgetc(fp)) != EOF);
return 0;
}
ungetc(c, fp);
}
return -1;
}
int skip_file_to_return(FILE *fp) {
int c;
while ((c = fgetc(fp)) != EOF) {
if (c == '\n' || c == '\r') {
return 0;
}
}
return 0;
}
int get_file_int(FILE *fp, int *reti) {
int c;
int i;
c = fgetc(fp);
if (c != EOF) {
if (isdigit(c)) {
i = 0;
do {
if (!isdigit(c)) {
break;
}
i = i * 10 + c - '0';
}while ((c = fgetc(fp)) != EOF);
ungetc(c, fp);
*reti = i;
return 0;
}
ungetc(c, fp);
}
return -1;
}
int get_file_text(FILE *fp, char *buf, int buf_len) {
int c;
if (buf_len > 0) {
c = fgetc(fp);
if (c != EOF) {
if (!isspace(c)) {
do {
if (buf_len <= 1 || isspace(c)) {
break;
}
*buf++ = c;
buf_len--;
}while ((c = fgetc(fp)) != EOF);
ungetc(c, fp);
*buf = '\0';
return 0;
}
ungetc(c, fp);
}
}
return -1;
}
int get_file_line(FILE *fp, GET_FILE_ELEMENT *ops, int n_ops, PLAYERINFO *pi) {
int i;
int retval;
for (i = 0; i < n_ops; i++) {
retval = (*ops[i])(fp, pi);
if (retval != 0) {
return retval;
}
}
return 0;
}
int get_file_space(FILE *fp, PLAYERINFO *pi) {
return skip_file_space(fp);
}
int get_file_return(FILE *fp, PLAYERINFO *pi) {
return skip_file_to_return(fp);
}
int get_file_playernumber(FILE *fp, PLAYERINFO *pi) {
return get_file_int(fp, &pi->playernumber);
}
int get_file_firstname(FILE *fp, PLAYERINFO *pi) {
return get_file_text(fp, pi->fisrtname, NAMELEN);
}
int get_file_lastname(FILE *fp, PLAYERINFO *pi) {
return get_file_text(fp, pi->lastname, NAMELEN);
}
int get_file_otab(FILE *fp, PLAYERINFO *pi) {
return get_file_int(fp, &pi->otab);
}
int get_file_noh(FILE *fp, PLAYERINFO *pi) {
return get_file_int(fp, &pi->noh);
}
int get_file_walks(FILE *fp, PLAYERINFO *pi) {
return get_file_int(fp, &pi->walks);
}
int get_file_rbis(FILE *fp, PLAYERINFO *pi) {
return get_file_int(fp, &pi->rbis);
}
int get_file_playerinfo(FILE *fp, PLAYERINFO *pi) {
static GET_FILE_ELEMENT ops[] = {
get_file_playernumber,
get_file_space,
get_file_firstname,
get_file_space,
get_file_lastname,
get_file_space,
get_file_otab,
get_file_space,
get_file_noh,
get_file_space,
get_file_walks,
get_file_space,
get_file_rbis,
get_file_return,
};
PLAYERINFO tmp_pi;
int retval;
retval = get_file_line(fp, ops, ALEN(ops), &tmp_pi);
if (retval == 0) {
*pi = tmp_pi;
return 0;
}
return retval;
}
int main(void) {
FILE *fp;
PLAYERINFO pi;
fp = fopen("test.txt", "r");
if (fp != NULL) {
while (get_file_playerinfo(fp, &pi) == 0) {
printf("%d %s %s %d %d %d %d\n",pi.playernumber,pi.fisrtname,
pi.lastname,pi.otab,
pi.noh,pi.walks,pi.rbis);
}
fclose(fp);
return 0;
}
return -1;
}
原文:=字符串
阅读(1006) | 评论(0) | 转发(0) |