Der*_*ick 4 c file-io buffer fgets
我正在使用popen来读取shell命令的输出.我将使用fgets逐行读取.我的问题是如何为我的char*缓冲区选择最佳缓冲区大小?我记得一位教授告诉我们要包含<limits.h>
和使用LINE_MAX
这些东西.它在我的Mac上工作正常,但LINE_MAX
在Linux上却没有.
这个邮件列表存档提出了同样的问题,但没有回答我的问题 http://bytes.com/topic/c/answers/843278-not-able-locate-line_max-limits-h
什么<limits.h>
时候没有定义LINE_MAX
,看看_POSIX2_LINE_MAX
,至少需要2048.我通常使用4096.
还要查找(新)POSIX函数getline()
和getdelim()
- 都在同一个URL上.这些必要时分配内存.
posix2_line_max.c
)#include "posixver.h"
#include <limits.h>
#include <stdio.h>
int main(void)
{
printf("%d\n", _POSIX2_LINE_MAX);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
2048
Run Code Online (Sandbox Code Playgroud)
posixver.h
#ifndef JLSS_ID_POSIXVER_H
#define JLSS_ID_POSIXVER_H
/*
** Include this file before including system headers. By default, with
** C99 support from the compiler, it requests POSIX 2001 support. With
** C89 support only, it requests POSIX 1997 support. Override the
** default behaviour by setting either _XOPEN_SOURCE or _POSIX_C_SOURCE.
*/
/* _XOPEN_SOURCE 700 is loosely equivalent to _POSIX_C_SOURCE 200809L */
/* _XOPEN_SOURCE 600 is loosely equivalent to _POSIX_C_SOURCE 200112L */
/* _XOPEN_SOURCE 500 is loosely equivalent to _POSIX_C_SOURCE 199506L */
#if !defined(_XOPEN_SOURCE) && !defined(_POSIX_C_SOURCE)
#if __STDC_VERSION__ >= 199901L
#define _XOPEN_SOURCE 600 /* SUS v3, POSIX 1003.1 2004 (POSIX 2001 + Corrigenda) */
#else
#define _XOPEN_SOURCE 500 /* SUS v2, POSIX 1003.1 1997 */
#endif /* __STDC_VERSION__ */
#endif /* !_XOPEN_SOURCE && !_POSIX_C_SOURCE */
#endif /* JLSS_ID_POSIXVER_H */
Run Code Online (Sandbox Code Playgroud)
在Ubuntu 12.04衍生产品上测试; 命令行:
gcc -g -O3 -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Werror posix2_line_max.c -o posix2_line_max
Run Code Online (Sandbox Code Playgroud)
man getline
另请参阅http://www.gnu.org/s/libc/manual/html_node/Line-Input.html以及getline()
vs. fgets()
vs. 的讨论gets()
.一直受到SO的影响比我更重要.