c - 在没有最大缓冲区长度的情况下从 C 中的标准输入读取

标签 c

以下代码设置从标准输入读取的最大行大小。我宁愿不对特定的行长度进行硬编码,而是可以灵活地处理任何缓冲区长度。允许处理任何规模的好策略是什么?

如果这些策略复杂得多,有没有办法至少保证 getline 不会溢出?谢谢。

 #include<stdlib.h>
 #include<stdio.h>
 #include<string.h>

 #define P 20

 int main()
 {
   size_t size = 1920;
   char *line;
   // record row; /* structure to store fields */
   char tokens[P][41];
   int p;
   char delims[] = ",";     /* ", |" */
   char *result = NULL;

   line = ( char * ) malloc( size + 1 );

   while( getline(&line, &size, stdin) != -1 )
   {
      /* chomp */
      line[strlen(line)-1] = '\0';

      /* load char array */
      result = strtok( line , delims );
      p = 0;
      while( result != NULL && ( p < P ) ) 
      {
         strcpy( tokens[p++] , result );
         result = strtok( NULL, delims );
      }

      if (p != P)
      {
         fprintf(stderr,"Wrong number of input fields.\nFormat: ID,x1, ... ,x%d\n",P);
     exit(-1);
      }

      /* load record ( atol, atof etc... , skipped for brevity ) and work with record */

      return 0;
 }

最佳答案

您可以让 getline 为您分配内存(这是使用 non-standard getline function over the standard fgets function 的全部要点)。来自 getline 手册页:

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (The value in *n is ignored.)

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc, updating *lineptr and *n as necessary.

所以你可以这样做:

line = NULL;
while (getline(&line, &size, stdin))
{
    // ... Do stuff with `line`...
}
free(line);

(或者让您的代码保持原样,因为 getline 将为您调整分配的缓冲区大小。)

关于c - 在没有最大缓冲区长度的情况下从 C 中的标准输入读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838676/

相关文章:

c - 如何用C实现XOR加密从客户端发送数据到服务器

c - 将管道作为参数传递给 sort -m

无法从 TextView 获取 GtkTextBuffer - C、GTK3

c - 尝试声明在 C 中使用 typedef 定义的结构时出错

c - 桌面环境之外的基于 GTK 的应用程序

c - 使用 srand 和 rand,经过几次迭代后我得到相同的数字

c++ - select() 在一个简单的自制 p2p 程序中与 udp 交换 "musicdata"的问题

c - SIGINT 的信号处理程序

c - 标记数据包以通过原始套接字发送

c++ - 在 Intellij IDEA for Windows 中配置 C++ SDK