C言語による簡単なプロファイル内容の読み取りと修正

7679 ワード

実行環境:ubuntu 14.04
この方法は小さなプロファイルに適しており、大きなファイルには適していません.
IP=192.168.1.20 MASK=255.255.255.0 DNS=192.168.1.1
#include 
#include 
#include 
#include 
#include 

#define STR_NETWORKCFG_FILE "./net.conf"

struct info_t{
  char name[20];
  char data[60];
};
/* (name) result */
int GetFile_Info(char *name,char *result)
{
  char linebuffer[100] = {0};
  char buffer1[100] = {0};
  char buffer2[100] = {0};
  uint8_t flag = 0;
  int buffer_size=0;
  FILE *fp = fopen(STR_NETWORKCFG_FILE, "r");
  if(fp == NULL)
  {
      printf("open error");
      return 1;
  }
  while(1)
  {
      char *ret = fgets(linebuffer, 100, fp);
      if(ret == NULL)
      {
        break;
      }
      sscanf(linebuffer, "%[^=]=%[^=]", buffer1,buffer2);
      if(!strcmp(name, buffer1))
      {
         buffer_size=strlen(buffer2);
         memcpy(result,buffer2,buffer_size);
        result[buffer_size-1]='\0';//remove the 
flag = 1; break; } memset(buffer1,0,sizeof(buffer1)); memset(buffer2,0,sizeof(buffer2)); memset(linebuffer,0,sizeof(linebuffer)); } fclose(fp); if(flag != 1) return 1; return 0; } /* , , , , */ int ChangeFile_Info(char *name,char *writedata) { int i; uint8_t flag = 0,cnt = 0; struct info_t info[12]; char linebuffer[256] = {0}; char buffer[80]; FILE *fp = fopen(STR_NETWORKCFG_FILE, "r"); if(fp == NULL) { printf("open error"); return 1; } for(i = 0 ; i < 12 ; i++) { char *ret = fgets(linebuffer, 256, fp); if(ret == NULL) { break; } sscanf(linebuffer, "%[^=]=%[^=]", info[i].name,info[i].data); if(!strcmp(info[i].name, name)) { memcpy(info[i].data,writedata,strlen(writedata)); info[i].data[strlen(writedata)] = '
'
; info[i].data[strlen(writedata)+1] = '\0'; flag = 1; } memset(linebuffer,0,sizeof(linebuffer)); cnt++; } fclose(fp); if(flag) { fp = fopen(STR_NETWORKCFG_FILE,"w"); if(fp == NULL) { return 1; } for(i = 0 ; i < cnt ; i++) { memset(buffer,0,sizeof(buffer)); sprintf(buffer,"%s=%s",info[i].name,info[i].data); fprintf(fp,"%s",buffer); } fclose(fp); } else return 1; return 0; } int main() { char result[100] = {0}; char *writedata = "192.168.10.33"; GetFile_Info("IP",result); printf("result:%s
"
,result); ChangeFile_Info("IP",writedata); GetFile_Info("IP",result); printf("result:%s
"
,result); return 0; }

コード実行結果:result:192.168.1.20 result:192.168.10.33ファイルを開いて表示し、IP=192.168.10.33