使用struct数组从文件读取的问题

时间:2011-01-25 01:57:24

标签: c

在函数read_conf函数中,我从配置文件中读取,当我使用print函数时,它会根据需要显示结构。

当我调用Display功能时,会出现读取问题,因为它只显示读取功能中的最后一个条目。

   struct {
     char *ext;
     char *filetype;
    } extensions [10];

void read_conf()
{
 char buf[BUFSIZE];
 char *free1 = NULL;
 char *free2 = NULL;
 FILE *fp;
 fp=fopen("config.conf", "r");
 int i_mime = 0;
 while(fgets(buf,sizeof(buf), fp))
 {
  if(!strncmp(buf,"Listen ",7))
  {
   Port_serv_list = &buf[7];   
   printf("Port number read from conf file is : %s\n", Port_serv_list);
  }  
  if(!strncmp(buf,"DocumentRoot ",13))
  {
   Dir = &buf[13];   
   printf("Directory read from conf file is : %s\n", Dir);
  }  
  if (buf[0] == '.')
  {  
   free1 = strtok(buf," ");   
   extensions[i_mime].ext = &free1[1];

   free2 = strtok(NULL," "); 
   extensions[i_mime].filetype = free2;
   printf("ext: %s\n",extensions[i_mime].ext);
   printf("filetype: %s\n%d\n",extensions[i_mime].filetype, i_mime);
   i_mime++;   
   //printf("Data from conf file \": %s\n",buf);
  }
 }
}

void Display_Content_Conf()
{
 int j_mime = 0;
 printf("Displaying content of Extension Structure array:""\n");
 for(j_mime;j_mime<=7;j_mime++)
 {
  printf("ext: %s\n",extensions[j_mime].ext);
  printf("filetype: %s\n%d\n",extensions[j_mime].filetype, j_mime);
 }
}

输出:

ext: htm
filetype: text/html

0
ext: html
filetype: text/html

1
ext: txt
filetype: text/plain

2
ext: jpeg
filetype: image/jpeg

3
ext: jpg
filetype: image/jpeg

4
ext: png
filetype: image/png

5
ext: gif
filetype: image/gif

6
ext: bmp
filetype: image/bmp

7

显示Extension Structure数组的内容:

ext: bmp
filetype: image/bmp

0
ext: bmp
filetype: mage/bmp

1
ext: bmp
filetype: image/bmp

2
ext: bmp
filetype: mage/bmp

3
ext: bmp
filetype: image/bmp

4
ext: bmp
filetype: image/bmp

5
ext: bmp
filetype: image/bmp

6
ext: bmp
filetype: image/bmp

7

1 个答案:

答案 0 :(得分:2)

看起来extensions结构中的指针指向buf,每次通过循环时都会被覆盖(并在退出read_conf时取消分配,因此事实如此你看到任何有效的东西都是未定义的行为。)

您需要在strdup返回的字符串上调用strtok,以便将它们放入新分配的动态内存中,以便安全地存储它们。像这样:

free1 = strtok(buf," ");   
extensions[i_mime].ext = strdup(&free1[1]);

free2 = strtok(NULL," "); 
extensions[i_mime].filetype = strdup(free2);

请记住free() strdup当您不再需要它们时返回的字符串。如果运气不好,你的C环境不能提供strdup功能(它不在ANSI C中,但在POSIX中是),你可以提供它 - 它很简单:

/* Duplicates a supplied string. */
char *strdup(const char *input)
{
    /* Required buffer size is the string length, plus 1 for terminator. */
    size_t size = strlen(input) + 1;

    /* Allocate buffer.  If it fails, return NULL for failure. */
    char *dup = (char *) malloc(size);
    if (dup == NULL) return NULL;

    /* Now copy the string data into the newly allocated buffer and return it. */
    memcpy(dup, input, size);
    return dup;
}