1、使用VS新建空工程,直接点击确定。
2、新建c文件,用于C语言编译器。
3、然后输入main.c文件。
4、写入下面代码#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_LINE 1024void ReadTxt(char* pFilePath){ char buf[MAX_LINE] /*缓冲区*/ FILE *fp /*文件指针*/ int len。
5、编译完成后,运行exe程序,把一个数组存放到txt文件中去。
C语言把一个结构体数组写入文件分三步:
1、以二进制写方式(wb)打开文件
2、调用写入函数fwrite()将结构体数据写入文件
3、关闭文件指针
相应的,读文件也要与之匹配:
1、以二进制读方式(rb)打开文件
2、调用读文件函数fread()读取文件中的数据到结构体变量
3、关闭文件指针
参考代码如下:
#include<stdio.h>struct stu {
char name[30]
int age
double score
}
int read_file()
int write_file()
int main()
{
if ( write_file() < 0 ) //将结构体数据写入文件
return -1
read_file() //读文件,并显示数据
return 0
}
int write_file()
{
FILE *fp=NULL
struct stu student={"zhang san", 18, 99.5}
fp=fopen( "stu.dat", "wb" ) //b表示以二进制方式打开文件
if( fp == NULL ) //打开文件失败,返回错误信息
{
printf("open file for write error\n")
return -1
}
fwrite( &student, sizeof(struct stu), 1, fp ) //向文件中写入数据
fclose(fp)//关闭文件
return 0
}
int read_file()
{
FILE *fp=NULL
struct stu student
fp=fopen( "stu.dat", "rb" )//b表示以二进制方式打开文件
if( fp == NULL ) //打开文件失败,返回错误信息
{
printf("open file for read error\n")
return -1
}
fread( &student, sizeof(struct stu), 1, fp ) //读文件中数据到结构体
printf("name=\"%s\" age=%d score=%.2lf\n", student.name, student.age, student.score ) //显示结构体中的数据
fclose(fp)//关闭文件
return 0
}
fwrite(const void*buffer,size_t size,size_t count,FILE*stream)
(1)buffer:指向结构体的指针(数据首地址)
(2)size:一个数据项的大小(一般为结构体大小)
(3)count: 要写入的数据项的个数,即size的个数
(4)stream:文件指针。