linux下标准I/O操作

来源:互联网 发布:阿里云1m带宽慢不慢 编辑:程序博客网 时间:2024/05/16 07:15
/*** writerec.c****/#include <stdio.h>#include <stdlib.h>struct record {char name[10];int age;};int main(void){int result;struct record array[2] = {{"Ken", 24}, {"Knuth", 28}};FILE *fp = fopen("recfile", "w");if (fp == NULL) {perror("Open file recfile");exit(1);}result=fwrite(array, sizeof(struct record), 2, fp);/*fwrite函数,第一个参数是数据存储的数组,第二个是每条记录的大小,第三个是记录数,第四个是文件指针,返回写入的记录数。*/printf("write %d records\n",result);if(result<2){printf("file write eror\n");}fclose(fp);return 0;}/***** readrec.c*****/#include <stdio.h>#include <stdlib.h>struct record {char name[10];int age;};int main(void){struct record array[2];FILE *fp = fopen("recfile", "r");if (fp == NULL) {perror("Open file recfile");exit(1);}fread(array, sizeof(struct record), 2, fp);printf("Name1: %s\tAge1: %d\n", array[0].name, array[0].age);printf("Name2: %s\tAge2: %d\n", array[1].name, array[1].age);fclose(fp);return 0;}

0 0
原创粉丝点击