文件读写操作

来源:互联网 发布:java语言程序设计 一 编辑:程序博客网 时间:2024/06/11 04:16

1.打开一个write.txt文件,向该文件中写入一个Student学生的详细信息,若该文件不存在,则创建一个文件;其中考虑了大端与小端的问题;

/*************************************************************************    * File Name: fileWrite.c    * Author: lixiaogang    * Mail: 2412799512@qq.com     * Created Time: 2017年06月06日 星期二 20时29分43秒 ************************************************************************/#include<stdio.h>#include<netinet/in.h>#include<sys/stat.h>#include<sys/types.h>#include<fcntl.h>#include<stdlib.h>#include<string.h>#include<unistd.h>struct Student{    char *name;    int score;    int age;};int main(int argc,char *argv[])  {    struct Student _s;    char buf[1024];    int len,fd;    memset(buf,0x00,sizeof(buf));    puts("input name:");        fgets(buf,sizeof(buf),stdin);    len = strlen(buf);    buf[len-1] = '\0';    /*strdup 字符串赋值函数*/    _s.name = strdup(buf);    puts("input score:");    fgets(buf,sizeof(buf),stdin);    len = strlen(buf);    buf[len -1] = '\0';    _s.score = atoi(buf);    puts("input age:");    fgets(buf,sizeof(buf),stdin);    len = strlen(buf);    buf[len -1 ] = '\0';    _s.age = atoi(buf);    fd = open("write.txt",O_WRONLY|O_CREAT|O_TRUNC,0777);    if(fd < 0){        perror("open");        return -1;    }    //考虑大端小端    int _temp;    len = strlen(_s.name);    _temp = htonl(_s.age);    write(fd,&_temp,sizeof(_temp));    _temp = htonl(_s.score);    write(fd,&_temp,sizeof(_s.score));    _temp = htonl(len);    //作为一个标记    write(fd,&_temp,sizeof(_temp));    write(fd,_s.name,strlen(_s.name));    close(fd);    return 0;  }

2.读出write.txt文件中的内容,并且将其打印出来;在打印之前先将大端数据转换为小端字节序数据;

/*************************************************************************    * File Name: fileRead.c    * Author: lixiaogang    * Mail: 2412799512@qq.com     * Created Time: 2017年06月06日 星期二 20时55分20秒 ************************************************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<netinet/in.h>#include<sys/stat.h>#include<fcntl.h>#include<sys/types.h>#include<unistd.h>struct Student{    char *name;    int score;    int age;};int main(int argc,char *argv[])  {    struct Student _s;    int fd;    fd = open("write.txt",O_RDONLY);    if(fd < 0){        perror("open");        return -1;    }    int _temp;    read(fd,&_temp,sizeof(_temp));    _s.age = ntohl(_temp);    read(fd,&_temp,sizeof(_temp));    _s.score = ntohl(_temp);    read(fd,&_temp,sizeof(_temp));    int len = ntohl(_temp);    _s.name = malloc(len + 1);    _s.name[len] = '\0';    read(fd,_s.name,len);    printf("name = %s,age = %d,score = %d\n",_s.name,_s.age,_s.score);    close(fd);    free(_s.name);    return 0;  }
原创粉丝点击