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
|
#include <stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
void
unpack (char *buf, char *format, ...)
{
va_list ap;
char *s;
int len;
int maxstrlen = 0;
int count;
va_start(ap, format);
while (*format != '\0')
{
switch (*format)
{
case 'A':
/* String format */
s = va_arg (ap, char *);
len = strlen (buf);
if (maxstrlen > 0 && len > maxstrlen)
count = maxstrlen;
else
count = len;
memcpy(s, buf, count);
s[count] = '\0';
buf += count;
break;
default:
/* Track max str len */
if (isdigit (*format))
maxstrlen = maxstrlen * 10 + (*format - '0');
}
if (! isdigit (*format))
maxstrlen = 0;
format++;
}
va_end (ap);
}
int
chomp (char *s)
{
int chomped = 0;
char *p = strchr (s, '\n');
if (p != NULL)
{
*p = '\0';
chomped = 1;
}
return chomped;
}
int
main (void)
{
FILE *fp;
char buf [100];
char id [2+1], day [2+1], month [20+1];
fp = fopen ("month.txt", "r");
while (fgets (buf, 100, fp))
{
chomp (buf);
unpack (buf, "2A2AA", id, day, month);
printf ("> id='%s', day='%s', month='%s'\n", id, day, month);
}
fclose (fp);
return 0;
} |
Partager