首页 文章

有没有办法动态设置我们从fgets()获得的字符串的大小?

提问于
浏览
0

我有一个变量char * cmd,我想从fgets()中存储一个字符串 . 有没有办法使用malloc或类似的变量动态分配内存?或者我是否必须预定义其大小并在之后终止null?之前,我将cmd的大小预定义为100,但我试图找到我在哪里得到分段错误 .

char *cmd;

fgets(cmd, n, stdin);

然后我尝试使用带有空格作为分隔符的strtok()来标记cmd字符串 .

1 回答

  • 1

    正如我在上面的评论中所说,这不是为了寻找 . 如果你想自己动手,那么这样做的方法是动态分配(和重新分配)内存来存储你从 fgets() 获得的结果 . 你可以判断 fgets() 何时到达行的末尾,因为它要么突然到达文件的末尾(在这种情况下它将返回 NULL ),或者因为它返回的最后一个字符将是换行符 .

    这是一个示例函数 . 请注意,我使用 strrchr() 从缓冲区末尾向后搜索换行符 . 如果我们得到一个命中,我们确保在返回的字符串中抛出换行符,并确保突破 while() 循环,这样我们就不会再次调用 fgets() 并开始获取下一行 .

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // NOTE:  dygetline() allocates memory!  Do not disregard the return and
    // remember to free() it when you're done! 
    
    #define BSZ 1024
    
    char *dygetline(FILE * restrict stream) {
      char *ret = NULL;
      char *temp = NULL;
      size_t retalloc = 1;
      char buffer[BSZ];
      size_t buflen = 0;
      char *nlsrch;
    
    
      while (NULL != fgets(buffer, BSZ, stream)) {
        nlsrch = strrchr(buffer, '\n');
    
        if (nlsrch) *nlsrch = '\0';     // Remove newline if exists
    
        // Get the size of our read buffer and grow our return buffer
        buflen = strlen(buffer);
        temp = realloc(ret, retalloc + buflen);
    
        if (NULL == temp) {
          fprintf(stderr, "Memory allocation error in dygetline()!\n");
          free(ret);
          return NULL;
        }
    
        ret = temp;                     // Update return buffer pointer
    
        strcpy((ret+retalloc-1), buffer);  // Add read buffer to return buffer
        retalloc = retalloc + buflen;      // Housekeeping
    
        if (nlsrch) break;              // If we got a newline, stop
      }
    
      // If there was a file read error and fgets() never got anything, then
      // ret will still be NULL, as it was initialized.  If the file ended
      // without a trailing newline, then ret will contain all characters it
      // was able to get from the last line.  Otherwise, it should be well-
      // formed. 
    
      return ret;
    }
    

相关问题