在linux下用C语言写的关于数据文件插入操作的简单程序,运行有问题。。
如题,编译可以通过,运行不对,,代码如下:程序代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define TM_L 14 typedef struct _calllist calllist; struct _calllist { long id; int type; long telnum; char btime[TM_L]; long tcount; float charge_rate; float charge_sum; }; typedef struct _calllist calllist; int selectdb(calllist **cl,int f) { printf ("hehihei"); int i = sizeof(calllist); long length = lseek(f,0,SEEK_END); if (length < i) { puts("empty"); return -1; } if (*cl != NULL) { free(*cl); } *cl = malloc(length); lseek(f,0,SEEK_SET); if (read(f, *cl, length) != length) { perror("error"); return -2; } printf ("haha"); return 0; } int insertdb(calllist * cr,int f,calllist *cl) { printf ("dfjdk"); int i; i = sizeof(calllist); int length = lseek(f,0,SEEK_END); cr -> id = (cl + length/i - 1) -> id + 1; printf ("1"); lseek(f,0,SEEK_END); if (write(f,cr,i) != i) { perror("error"); return -1; } printf ("4"); return 0; } void printdb(calllist * cl,int f) { int i = sizeof(calllist); long length = lseek(f,0,SEEK_END); int j; char btime[TM_L + 1] = {0}; for (j = 0; j<length/i; j++) { memcpy(btime, (cl+j) -> btime,TM_L); printf ("ahha"); 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; int res; calllist cr = {1,0,12354,"34343434343444",30,3.55,3.44}; calllist *cl; cl = NULL; f = open("listdb",O_RDWR | O_CREAT,0664); if (f == -1) { perror("error"); return 1; } puts("the original file:"); res = selectdb(&cl,f); if (res == -2) { return 1; } else if(res == 0) { printdb(cl,f); } puts("insert hou file:"); insertdb(&cr,f,cl); printf ("djfkd"); res = selectdb(&cl,f); if (res == -2) { return 1; } else if(res == 0) { printdb(cl,f); } close(f); return 0; }
运行显示:Segmentation fault(core dumped),应该是insert函数不对,这是为什么啊,,希望大家帮忙看看