文件读写操作

xiaoxiao2021-02-28  121

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; }

博主最新开了一个网店 [ 华少潮牌男装店 ],款式多样,价格实惠,质量保证。欢迎各位读者进店查看。购买时请说明是读者,优惠更大。期待你的光临!!!

转载请注明原文地址: https://www.6miu.com/read-26671.html

最新回复(0)