1.将结构体中的内容保存到配置文件中,记录结构体中的内容,防止丢失。
2.结构体定义如下:
#ifndef _TSK_CTL_H_
#define _TSK_CTL_H_
#define LENGTH 16
#define USER_NAME_LEN 16
#define PASSWORD_LEN 16
typedef struct user_ifm {
char username_1[LENGTH];
char password_1[LENGTH];
char username_2[LENGTH];
char password_2[LENGTH];
}USER_IFM;
#endif
2.fwrite.c文件如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "user_pwd.h"
int main()
{
USER_IFM user_buf;
FILE *fp_w = NULL;
FILE *fp_r = NULL;
size_t bytes_w = 0;
size_t bytes_r = 0;
fp_r = fopen("/app/app_user.cfg","rb+");
if (fp_r == NULL)
{
perror("fail to open read!");
//exit (1);
return -1;
}
printf("%s:%d \n", __FUNCTION__,__LINE__);
memset(&user_buf, 0, sizeof(USER_IFM));//必须的清空结构体
//保存页面的值
bytes_r = fread (&user_buf,sizeof(USER_IFM),1,fp_r);
printf("%s:%d \n", __FUNCTION__,__LINE__);
if (bytes_r < 0)
{
perror("fail to fread");
//exit(1);
return -1;
}
memset(user_buf.username_1,0,sizeof(user_buf.username_1));
memset(user_buf.password_1,0,sizeof(user_buf.username_1));
strncpy(user_buf.username_1,"admin",5);
strncpy(user_buf.password_1,"admin",5);
//保存页面的值
fp_w = fopen("/app/app_user.cfg","wb+");
if (fp_w == NULL)
{
perror("fail to open write!");
//exit (1);
return -1;
}
printf("%s:%d \n", __FUNCTION__,__LINE__);
//保存页面的值
bytes_w = fwrite (&user_buf,sizeof(USER_IFM),1,fp_w);
printf("%s:%d \n", __FUNCTION__,__LINE__);
if (bytes_w < 0)
{
perror("fail to fwrite");
//exit(1);
return -1;
}
fflush(fp_w);
fclose(fp_r);
fclose(fp_w);
return 0;
}
注意:如果有想对结构体中的内容进行更改,必须在往配置文件中写内容时,先要把配置文件中原有的内容读取出来,如果不读取的话,第二次读取配置文件中的内容是就会出现乱码,由于没有进行读取而是直接进行了写入,这样会把以前的内容给覆盖掉,读取出来的内容就为空,或者是乱码。在每次读取时都要将结构体中的内容给清空掉。