#include
#include
#include
#include
#include
#include
#define BOOKNAME "address_book.txt"
int fd;
void menu();
int file_open(const char *pathname);
void *file_write(int fds, char *buf);
//申明一个address_book结构体
struct address_book{
char name[20]; //名字
char addr[50]; //家庭住址
char tel[12]; //手机号
char qq[12]; //qq号
char mail[30]; //邮箱
};
//定义一个struct address_book指针
struct address_book *abook;
int main()
{
menu();
file_open(BOOKNAME);
printf("fd is : %d\n", fd);
//申请一块动态内存,用来存放结构体,所以动态内存的大小和返回值都必须和结构体一样
//malloc失败的时候会返回NULL
abook = (struct address_book *)malloc(sizeof(struct address_book));
if(abook == NULL)
{
printf("malloc fialed\n");
return;
}
//内存拷贝,将第二个参数的内容赋值到第一个参数指向到内存,复制的大小是第三个参数
memcpy(abook->name, "weijie", 7);
memcpy(abook->addr, "hjwlw", 6);
memcpy(abook->tel, "18810867651", 12);
memcpy(abook->qq, "78080458", 9);
memcpy(abook->mail, "wj78080458@163.com\n", 19);
//将abook的内容写入到文件fd
file_write(fd, (char *)abook);
}
//菜单,用户可以根据菜单的提示操作
void menu()
{
system("clear"); //清屏
printf("|-----------------------------------------------------|\n");
printf("| please input your operation |\n");
printf("|-----------------------------------------------------|\n");
printf("| 1、 query 查询 |\n");
printf("| 2、 insert增加 |\n");
printf("| 3、 delete删除 |\n");
printf("| 4、 exit 退出 |\n");
printf("|-----------------------------------------------------|\n");
}
int file_open(const char *pathname)
{
//以读写的方式打开pathname, 打开之后文件指针在最后
fd = open(pathname, O_RDWR|O_APPEND);
//如果打开成功返回文件描述符,如果失败返回-1
if(fd<0)
{
printf("open data file error\n");
return -1;
}
return fd;
}
void *file_write(int fds, char *buf)
{
int num;
write(fds, ((struct address_book *)buf)->name, sizeof(((struct address_book *)buf)->name));
write(fds, "\t\t", 2);
write(fds, ((struct address_book *)buf)->addr, sizeof(((struct address_book *)buf)->addr));
write(fds, "\t\t", 2);
write(fds, ((struct address_book *)buf)->tel, sizeof(((struct address_book *)buf)->tel));
write(fds, "\t\t", 2);
write(fds, ((struct address_book *)buf)->qq, sizeof(((struct address_book *)buf)->qq));
write(fds, "\t\t", 2);
write(fds, ((struct address_book *)buf)->mail, sizeof(((struct address_book *)buf)->mail));
}
注意:write(fds, "\t\t", 2); 这里里面的制表符 ‘\t’ ,以前的学习中代表是8个,在这里却是一个,须要注意
阅读(1018) | 评论(0) | 转发(0) |