以下代码设置从标准输入读取的最大行大小。我宁愿不对特定的行长度进行硬编码,而是可以灵活地处理任何缓冲区长度。允许处理任何规模的好策略是什么?
如果这些策略复杂得多,有没有办法至少保证 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
isNULL
, thengetline()
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 amalloc
-allocated buffer*n
bytes in size. If the buffer is not large enough to hold the line,getline()
resizes it withrealloc
, 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/