[英]Reading from stdin using read(..) and figuring out the size of the buffer
我想知道是否有人可以告訴我,當使用read(...)
從stdin read(...)
輸入時是否有動態分配緩沖區的方法例如:
n = read(0, buffer, sizeof ?);
如何確保從stdin
(此處為0)讀取的字節數與buffer
的相同?
你不能。 您可以read
固定大小的緩沖區,例如:
char buf[BUF_SIZE];
int num_read = read(0, buf, BUF_SIZE);
然后弄清楚是否還有更多數據可用(通常通過檢查num_read
是否等於BUF_SIZE
,但在某些情況下,您可能需要解釋數據本身)。 如果有,那么你再做一次閱讀。 等等。
由您來處理連接所有讀取數據。
你不能(除非你有預知技能)弄清楚你會得到什么的大小。
但是read方法允許你逐個讀取stdin的內容,如果你將read()調用放入( while your_stop_condition
)循環中,你將能夠通過數據包讀取stdin所需的所有東西。
char buffer_to_read[SIZE];
int bytes=0;
while your_stop_condition
{
bytes = read(0, buffer_to_read, SIZE);
// do what you want with your data read
// if bytes < SIZE, you read an EOF
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.