函数声明
#ifndef __VECTOR_H__
#define __VECTOR_H__
typedef struct{
int *fd;
int counter;
int max_counter;
}VectorFD;
extern VectorFD* create_vector_fd(void);
extern void destroy_vector_fd(VectorFD *);
extern int get_fd(VectorFD *,int index);
extern int mremove(VectorFD *,int fd);
extern void add_fd(VectorFD *,int fd);
#endif
函数定义
#include <malloc.h>
#include <assert.h>
#include <stdlib.h>
#include <memory.h>
#include "vector_fd.h"
static void encapacity(VectorFD *vfd){
if(vfd->counter >= vfd->max_counter){
int *fds=(int*)calloc(vfd->counter+5,sizeof(int));
assert(fds!=NULL);
memcpy(fds,vfd->fd,sizeof(int)*vfd->counter);
free(vfd->fd);
vfd->fd=fds;
vfd->max_counter += 5;
}
}
static int indexof(VectorFD *vfd,int fd){
int i=0;
for(;i<vfd->counter;i++){
if(vfd->fd[i]==fd) return i;
}
return -1;
}
VectorFD* create_vector_fd(void){
VectorFD *vfd=(VectorFD*)calloc(1,sizeof(VectorFD));
assert(vfd!=NULL);
vfd->fd=(int*)calloc(5,sizeof(int));
assert(vfd->fd!=NULL);
vfd->counter=0;
vfd->max_counter=0;
return vfd;
}
void destroy_vector_fd(VectorFD *vfd){
assert(vfd!=NULL);
free(vfd->fd);
free(vfd);
}
int get_fd(VectorFD *vfd,int index){
assert(vfd!=NULL);
if(index<0||index>vfd->counter-1)
return 0;
return vfd->fd[index];
}
int mremove(VectorFD *vfd,int fd){
assert(vfd!=NULL);
int index=indexof(vfd,fd);
if(index==-1) return -1;
int i=index;
for(;i<vfd->counter-1;i++){
vfd->fd[i]=vfd->fd[i+1];
}
vfd->counter--;
}
void add_fd(VectorFD *vfd,int fd){
assert(vfd!=NULL);
encapacity(vfd);
vfd->fd[vfd->counter++]=fd;
}
标签:vfd,多路复用,VectorFD,int,编程,fd,数组,NULL,counter
From: https://blog.csdn.net/m0_57264635/article/details/145111242