#include
#include
#include
#include
#include
#include
#include
typedef struct _calllist callist;
struct _calllist {
long id;
int type;
long telnum;
char btime[14];
long tcount;
float charge_rate;
float charge_sum;
};
int selectdb(callist **cl, int f)
{
int i = sizeof(callist);
long length = lseek(f, 0, SEEK_END);
if (length < i) {
puts("无记录");
return -1;
}
if (*cl != NULL)
free(*cl);
*cl = malloc(length);
lseek(f, 0, SEEK_SET);
if(read(f, *cl, length) != length) {
perror("读取数据失败");
return -2;
}
return 0;
}
int insertdb(callist *cr, int f, callist *cl)
{
int i = sizeof(callist);
int length = lseek(f, 0, SEEK_END);
cr -> id = (cl + length / i - 1) -> id + 1;
lseek(f, 0, SEEK_END);
if(write(f, cr, i) != i) {
perror("插入记录失败");
return -1;
}
return 0;
}
int changedb(callist *cr, int f, callist *cl)
{
int i = sizeof(callist);
long length = lseek(f, 0, SEEK_END);
long j;
for(j = 0; j <= length / i; j++) {
if ((cl + j) -> id == cr -> id)
break;
}
memcpy(cl + j, cr, i);
lseek(f, 0, SEEK_SET);
if(write(f, cl, length) != length) {
perror("读取数据失败");
return -1;
}
return 0;
}
int deletedb(callist *cr, int *f, callist **cl)
{
int i = sizeof(callist);
long length = lseek(*f, 0, SEEK_END);
long j;
for(j = 0; j <= length / i; j++) {
if ((*cl + j) -> id == cr -> id)
break;
}
memmove(*cl + j, *cl + j + 1, length - i * (j + 1));
length -= i;
close(*f);
*f = open("listdb", O_RDWR | O_TRUNC);
if(write(*f, *cl, length) != length) {
perror("读取数据失败");
return -1;
}
return 0;
}
void printdb(callist *cl, int f)
{
int i = sizeof(callist);
long length = lseek(f, 0, SEEK_END);
int j;
char btime[15] = {0};
for(j = 0 ;j < length / i; j++) {
memcpy(btime, (cl + j) -> btime, 14);
printf("%ld, %d, %ld, %14s, %ld, %1.2f, %1.2f\n",
(cl + j) -> id,
(cl + j) -> type,
(cl + j) -> telnum,
btime,
(cl + j) -> tcount,
(cl + j) -> charge_rate,
(cl + j) -> charge_sum);
}
}
int main()
{
int f;
callist cr = {1,0,12345,"20090301120011",30,0.36,0.36};
callist *cl;
cl = NULL;
f = open("listdb", O_RDWR | O_CREAT, 0664);
if (f == -1) {
perror("打开文件错误");
return 1;
}
puts("原始文件输出:");
if (selectdb(&cl, f) == -2)
return 1;
printdb(cl, f);
puts("插入操作后文件输出:");
insertdb(&cr, f, cl);
if (selectdb(&cl, f) == -2)
return 1;
printdb(cl, f);
puts("修改文件输出:");
if (selectdb(&cl, f) == -2)
return 1;
printdb(cl, f);
cr.id = 2;
cr.telnum = 54321;
deletedb(&cr, &f, &cl);
res = selectdb(&cl, f);
if (res == -2) {
puts("读取数据文件错");
return 1;
}
printdb(cl, f);
close(f);
return 0;
}
运行
文章评论(0条评论)
登录后参与讨论