程序代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node NODE, * PNODE;
typedef const PNODE PCNODE;
struct node {
char bits[4];
PNODE next;
};
void * check(void * p);
PCNODE init_stack(void);
PCNODE push(PNODE pTop, const char * bits);
const char * pop(PNODE pTop);
int is_empty(PCNODE pTop);
void kill_stack(PNODE top);
char * number_format(long num, char * buf);
void * check(void * p) {
if(!p) {
fprintf(stderr, "There's a error in program and then program will to exit.\n");
system("pause");
exit(1);
}
return p;
}
PCNODE init_stack(void) {
PNODE pTop = (PNODE)malloc(sizeof(NODE));
check(pTop);
pTop->next = NULL;
return pTop;
}
PCNODE push(PNODE pTop, const char * bits) {
PNODE pNewNode = (PNODE)malloc(sizeof(NODE));
check(pNewNode);
strcpy(pNewNode->bits, bits);
pNewNode->next = pTop->next;
pTop->next = pNewNode;
return pNewNode;
}
const char * pop(PNODE pTop, char * bits) {
PNODE pTemp = pTop->next;
if(is_empty(pTop))
return NULL;
strcpy(bits, pTemp->bits);
pTop->next = pTemp->next;
free(pTemp);
return bits;
}
void kill_stack(PNODE pTop) {
char buf[4];
while(pop(pTop, buf))
;
free(pTop);
}
int is_empty(PCNODE pTop) {
return pTop->next == NULL;
}
char * number_format(long num, char * buf) {
int isNage = num < 0;
char * pTemp = buf;
char bits[4];
PNODE pTop = init_stack();
unsigned long temp = isNage ? ~(unsigned long)num + 1 : (unsigned long)num;
while(temp) {
sprintf(bits, "%d", temp % 1000);
push(pTop, bits);
temp /= 1000;
}
if(isNage) {
strcpy(buf, "-");
strcat(buf, pop(pTop, bits));
} else
strcpy(buf, pop(pTop, bits));
while(pop(pTop, bits)) {
strcat(buf, ",");
strcat(buf, bits);
}
kill_stack(pTop);
return buf;
}
int main(void) {
char fileName[128];
char buf[100];
long size;
long value;
FILE * fp;
scanf("%s", fileName);
check(fp = fopen(fileName, "rb"));
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
printf("Size of \"%s\" is %s bytes.\n", fileName, number_format(size, buf));
scanf("%ld", &value);
printf("%s\n", number_format(value, buf));
system("pause");
return 0;
}