从文件写入和读取结构体示例代码
来源:互联网 发布:计算机c语言自学教材 编辑:程序博客网 时间:2024/05/20 09:25
/****************************************************** author :杨志永* date :2012-04-15* E-mail:ljy520zhiyong@163.com* QQ :929168233** filename:structs_io.c** Sytem:Debian 6.0.4* GCC:4.6.3* Architecture:X86_64*******************************************************/#include <stdio.h>#include <stdlib.h>#define MAX 80struct student{ char name[MAX]; int number;};int main(int argc, char * argv[]){ FILE * file; int i; struct student writeStruct[2], readStruct[2], *write_ptr, *read_ptr; if ( (file=fopen("test.txt", "w+")) == NULL ) { printf("open test.txt failed!\n"); exit(EXIT_FAILURE); } write_ptr = writeStruct; read_ptr = readStruct; for (i=0; i<2; i++, write_ptr++) scanf("%s\t%d", write_ptr->name, &write_ptr->number); write_ptr = writeStruct; fwrite(write_ptr, sizeof(struct student), 2, file); rewind(file); fread(read_ptr, sizeof(struct student), 2, file); printf("read from read_ptr\n"); for (i=0; i<2; i++) { printf("name is : %s\n", read_ptr->name); printf("number is : %d\n", read_ptr->number); read_ptr++; } exit(EXIT_SUCCESS);}