[英]Reading characters into a limited buffer size
我有一個程序,接受字符並將它們讀入有限大小的緩沖區(在本例中為64)。 如果用戶輸入的字符超過64個,則必須拒絕整個輸入字符串,警告用戶輸入的字符過多,然后重新開始。 如果用戶點擊ctrl-D
(文件結尾),則程序必須退出。
因此,我的設計如下:將實際的基礎緩沖區設置為65個字符以適應換行符。 如果最后一個字符不是換行符,則用戶按ctrl-D
,程序退出。 如果緩沖區已滿(即包含65個字符),而最后一個不是換行符,則程序會假定給出了太多字符,因此它將進入循環並不斷將輸入讀入緩沖區,直到緩沖區讀取為止in以換行符結尾(在這種情況下,它會警告用戶限制並重新開始),或者將其縮短而不會以換行符結尾(在這種情況下,程序將終止)。
我的問題是,我該如何處理用戶准確輸入65個字符(或65的某個整數倍),然后按ctrl-D
? 按照程序當前的狀態,當緩沖區已滿並且沒有以換行符結尾時,它假定存在溢出,但是在這種情況下,我希望程序終止。 如何在收到65個字符的標量和ctrl-D
的標量倍數后終止程序?
#include <string.h>
#include <unistd.h>
#define BUFSIZE ( 65 )
int main( int argc, char* argv[] ) {
char* prompt = "myshell->";
char* tooMany = "Max characters (64) exceeded.\n";
int numInput;
int done = 0;
char input[ BUFSIZE ];
while( !done ) {
int cont = 0;
write( STDOUT_FILENO, prompt, strlen( prompt ) );
numInput = read( STDIN_FILENO, input, BUFSIZE );
if( input[ numInput - 1 ] == '\n' ) {
cont = 1;
} else {
if( numInput != BUFSIZE ) {
done = 1;
write( STDOUT_FILENO, "\n", strlen( "\n" ) );
} else {
int spill = 1;
while( spill ) {
numInput = read( STDIN_FILENO, input, BUFSIZE );
if( input[ numInput - 1 ] == '\n' ) {
spill = 0;
write( STDOUT_FILENO, tooMany, strlen( tooMany ) );
} else {
if( numInput != BUFSIZE ) {
spill = 0;
done = 1;
write( STDOUT_FILENO, "\n", strlen( "\n" ) );
}
}
}
}
}
/*done ingesting input. Now do something with it...*/
if( cont ) {
write( STDOUT_FILENO, input, numInput );
}
}
return 0;
}
約束:我只可以使用read
和write
功能,但不能從任何<stdio.h>
如果這確實是一個外殼,那為什么不處理更長的數據輸入流呢?
如果您的緩沖區限制為65/64字節,則編寫“讀取/處理或解析文本/讀取解析/等”的代碼。 環。
最終,當您的代碼收到CTRL-D時,然后執行所有解析的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.