一个可以做到让机器读取玩这个文件内容后自动获取了这个数组的数据的方法。
#include
#include
/*结构体定义*/
struct stdTmp{
char user[16]; //用户名
char pasd[16]; //密码
unsigned char age; //年龄
};
/*
函数名称:std_write
函数功能:将结构体,写入文件
传入参数:
const char *_file_path 文件路径
const struct stdTmp *_std 要写入的结构体
传出数据:
0 运行成功
-1 输入参数有误
-2 打开文件失败
-3 文件写入数据失败
注意事项:如果结构体过大的话,建议修改"写入结构体"区域,分片写入
编写人员:voidar
编写时间:2016-11-07
*/
int std_write(const char *_file_path, const struct stdTmp *_std){
FILE *fp = (FILE *)0x00; //文件操作
/*参数校验*/
if(!_file_path || !strlen(_file_path) || !_std) return -0x01;
/*打开文件*/
if( !(fp = fopen(_file_path, "wb+")) ) return -0x02;
/*写入结构体*/
if(fwrite((const void *)_std, sizeof(struct stdTmp), 0x01, fp) != 0x01) { fclose(fp); return -0x03; }
if(fflush(fp)){ fclose(fp); return -0x04; }
/*关闭文件*/
fclose(fp);
return 0x00;
}
/*
函数名称:std_read
函数功能:从文件中读取结构体
传入参数:
const char *_file_path 文件路径
struct stdTmp *_std 读取到的结构体体存储到该指针指向的结构体中
传出数据:
0 运行成功
-1 输入参数有误
-2 打开文件失败
-3 文件内容有误(长度不合法)
注意事项:无
编写人员:voidar
编写时间:2016-11-07
*/
int std_read(const char *_file_path, struct stdTmp *_std){
FILE *fp = (FILE *)0x00; //文件操作
/*参数校验*/
if(!_file_path || !strlen(_file_path) || !_std) return -0x01;
/*打开文件*/
if( !(fp = fopen(_file_path, "rb+")) ) return -0x02;
/*读取文件*/
if(fread((void *)_std, sizeof(struct stdTmp), 0x01, fp) != 0x01){ fclose(fp); return -0x03; }
/*关闭文件*/
fclose(fp);
return 0x00;
}
int main(){
int err = 0x00;
struct stdTmp mystd = {"admin", "123456", 12};
struct stdTmp getstd;
/*写入结构体*/
if(err = std_write("stdFile.txt", &mystd)){ printf("write error:%d\n", err); return err; }
/*读取结构体*/
if(err = std_read("stdFile.txt", &getstd)){ printf("read error:%d\n", err); return err; }
/*显示获取到的数据*/
printf(
"用户名:%s\n密码:%s\n年龄:%d\n",
getstd.user,
getstd.pasd,
getstd.age
);
}
用文件读取操作,将数组写入本地txt文件,用的时候,读文件
保存数组(结构体)数据到文本和保存单个数据到文本是一样的,只不过前者写的顺序和读的顺序要保持一致。
struct student{
char name;
char num;
int score;
}
#define N 100
struct student stu[N];
//write it to the txt
FILE *pFile = fopen( " data.txt" , "w+");
for( int i = 0; i< N ; i++ )
{
fprintf( pFile, "%c %c %d\n", stu[i].name, stu[i].num, stu[i].score );
}
fclose( pFile);
可以使用操作文件的方法