结构体原来还可以这么用 -- 结构体的高级应用 -- 原创安全字符串
最近研究发现,结构体还可以如同C++类一样构造使用,一时心血来潮写了个安全字符串结构,大家来看看,也请各位高手指点不足,谢谢啦。。
/* string.h */
#ifndef __STRING_H
#define __STRING_H
#include "string.cpp"
#endif
/* string.cpp */
typedef enum {FALSE=0,TRUE=1} BOOL;
typedef struct safe_string
{
/* variable */
char *contents;
int buffer_size;
/* construction */
void initalize(void);
/* member function */
void buf_allocate(int);
void buf_reallocate(int);
void buf_release(void);
BOOL autostring(const char *);
BOOL getstring(const char *);
int getlength(void);
/* destory */
void destory(void);
} string;
void safe_string::initalize(void)
{
contents=NULL;
buffer_size=0;
}
void safe_string::buf_allocate(int bufsize)
{
destory();
contents=(char *)malloc(bufsize);
if(!contents)
{
printf("No memory for allocating a new string!\n");
printf("Press any key to exit.\n");
getch();
exit(1);
}
buffer_size=bufsize;
}
void safe_string::buf_reallocate(int bufsize)
{
if(!contents)
contents=(char *)malloc(bufsize);
else
contents=(char *)realloc(contents,bufsize);
if(!contents)
{
printf("No memory for reallocating a new string!\n");
printf("Press any key to exit.\n");
getch();
exit(1);
}
buffer_size=bufsize;
}
void safe_string::buf_release(void)
{
int len=getlength();
contents=(char *)realloc(contents,len+1);
if(!contents)
{
printf("No memory for reallocating a string!\n");
printf("Press any key to exit.\n");
getch();
exit(1);
}
buffer_size=len+1;
}
BOOL safe_string::autostring(const char *s)
{
if(!s) return FALSE;
int len=strlen(s);
buf_allocate(len+1);
strcpy(contents,s);
return TRUE;
}
BOOL safe_string::getstring(const char *s)
{
if(!s) return FALSE;
if(!contents) return FALSE;
int len=strlen(s);
if(len+1>buffer_size)
return FALSE;
else
{
strcpy(contents,s);
return TRUE;
}
}
int safe_string::getlength(void)
{
char *p=contents;
int len=0;
while(*p++) len++;
return len;
}
void safe_string::destory(void)
{
if(contents) free(contents);
}
/* debug_string.cpp */
#include
#include
#include
#include
#include "string.h"
int main()
{
string s;
s.initalize();
s.autostring("Hello,world");
printf("%s,%d,%d\n",s.contents,s.buffer_size,s.getlength());
s.destory();
getch();
}