如何阅读和使用malloc和realloc用C任意长度的存储串? [英] How do I read and store string of arbitrary length using malloc and realloc in C?

查看:73
本文介绍了如何阅读和使用malloc和realloc用C任意长度的存储串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

typedef struct store
{
   char name[11];
    int age;
} store;

和主要功能(下面是它的一部分):

and a main function(below is part of it):

int main()
{
    int i=0;
    int inputs;
    char line[100];
    char name[11];
    char command[11];
    store read[3000];

    while(i < 3000 && gets(line) != NULL)  
    {
        int tempage;
        inputs = sscanf(line, "%10s %10s %d", command, name, &tempage);
        if (inputs == 3)
        {
            if (strcmp(command, "register") == 0)
             {
             strncpy(read[i].name, name,10);
             read[i].age = tempage;
             i++;
             ....

我需要修改它,以便它可以读取一行任意长度的,并用malloc和realloc从中也是任意长度的串行存储的名称

I need to modify it so that it can read a line of arbitrary length, and store the name from the line which is also a string of arbitrary length using malloc and realloc.

我应该如何处理这个?

推荐答案

您需要做的是阅读以较小的增量行了,你去调整你的缓冲区什么。

What you need to do is read the line in smaller increments, and resize your buffer as you go.

作为一个例子(未测试,并没有意思要特别优雅,只是一个例子):

As an example (not tested and not meaning to be particularly elegant, just an example):

char *readline(FILE *f)
{
   char *buf = NULL;
   size_t bufsz = 0, len = 0;
   int keep_going = 1;

   while (keep_going)
   {
      int c = fgetc(f);
      if (c == EOF || c == '\n')
      {
         c = 0;             // we'll add zero terminator
         keep_going = 0;    // and terminate the loop afterwards
      }

      if (bufsz == len)
      {
         // time to resize the buffer.
         //
         void *newbuf = NULL;
         if (!buf)
         {
            bufsz = 512; // some arbitrary starting size.
            newbuf = malloc(bufsz);
         }
         else
         {
            bufsz *= 2; // issue - ideally you'd check for overflow here.
            newbuf = realloc(buf, bufsz);
         }

         if (!newbuf)
         {
            // Allocation failure.  Free old buffer (if any) and bail.
            //
            free(buf);
            buf = NULL;
            break;
         }

         buf = newbuf;
      }

      buf[len++] = c;
   }

   return buf;
}

这篇关于如何阅读和使用malloc和realloc用C任意长度的存储串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆