我搜索了但沒有得到相關的答案,我正在linux機器上工作,我想檢查標準輸入流是否包含任何字符,而不從流中移除字符。檢查標準輸入是否爲空
回答
您可能想嘗試select()函數,並等待將數據輸入到輸入流中。
說明:
選擇()和PSELECT()允許一個程序來監視多個文件 描述,等到一個或多個文件描述符成爲 「準備就緒」的一些類的I/O操作(例如,可能的輸入)。如果可以在沒有阻塞的情況下執行對應的I/O操作(例如,讀取(2)),則文件 描述符被認爲是準備好的。
在你的情況,文件描述符將stdin
void yourFunction(){
fd_set fds;
struct timeval timeout;
int selectRetVal;
/* Set time limit you want to WAIT for the fdescriptor to have data,
or not(you can set it to ZERO if you want) */
timeout.tv_sec = 0;
timeout.tv_usec = 1;
/* Create a descriptor set containing our remote socket
(the one that connects with the remote troll at the client side). */
FD_ZERO(&fds);
FD_SET(stdin, &fds);
selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (selectRetVal == -1) {
/* error occurred in select(), */
printf("select failed()\n");
} else if (selectRetVal == 0) {
printf("Timeout occurred!!! No data to fetch().\n");
//do some other stuff
} else {
/* The descriptor has data, fetch it. */
if (FD_ISSET(stdin, &fds)) {
//do whatever you want with the data
}
}
}
希望它能幫助。
感謝您的即時rply,但是,我不想等待輸入流有數據, 它只是,如果流有數據,我需要做一些處理,如果它沒有數據,做一些其他處理。代碼不應該等待輸入, – 51k 2013-04-26 05:11:30
我仍然認爲這可以幫助@ 51k,讓我舉個例子。 – 2013-04-26 05:18:10
卡丘是在正確的道路上,但是select
只有當你處理一個以上的文件描述符必要的,stdin
不是POSIX文件描述符(int
);這是一個FILE *
。如果你走這條路線,你會想要使用STDIN_FILENO
。
這也不是一個非常乾淨的路線。我寧願使用poll
。通過指定0作爲timeout
,輪詢將立即返回。
如果沒有定義的事件都發生在任何選定的文件 描述符,則poll()應至少等待超時毫秒爲任何所選擇的文件描述符發生的 事件。 如果超時值 爲0,poll()應立即返回。如果 的值超時爲-1,則poll()應阻塞,直到發生請求的事件或 ,直到呼叫中斷。
struct pollfd stdin_poll = { .fd = STDIN_FILENO
, .events = POLLIN | POLLRDBAND | POLLRDNORM | POLLPRI };
if (poll(&stdin_poll, 1, 0) == 1) {
/* Data waiting on stdin. Process it. */
}
/* Do other processing. */
- 1. 如何檢查標準輸入是否爲空?
- 2. 如何檢查是否從標準輸入爲空或換行
- 3. 檢查輸入框是否爲空
- 4. 檢查輸入字段是否爲空
- 5. 檢查輸入是否爲空JQuery
- 6. 如何檢查輸入是否爲空?
- 7. Tkinter檢查輸入框是否爲空
- 8. 檢查JSP輸入是否爲「空」
- 9. 檢查輸入值是否爲空
- 10. JQuery檢查輸入是否爲空而不是檢查onload?
- 11. 如何檢查輸入任務中的輸入是否爲空?
- 12. 檢查textarea是否爲空(僅將'輸入'視爲空)?
- 13. 如何檢查輸入是否爲空/空
- 14. 檢查「cat」的輸出是否爲空
- 15. 檢查輸出是否爲空
- 16. 如何檢查傳入$ _POST的輸入是否爲空?
- 17. JQuery檢查輸入是否爲頁面加載時爲空
- 18. 檢查標籤是否爲空
- 19. 管道是否寫入標準輸入?
- 20. 如何查找輸入是否爲空?
- 21. 如何檢查輸入是否爲空格併爲空或不是?
- 22. 檢查輸入框是否爲焦點
- 23. Matlab檢查輸入是否爲非零
- 24. 檢查輸入是否爲整數
- 25. 檢查是否爲datetimepicker輸入值?
- 26. 檢查輸入是否爲數字C
- 27. 檢查輸入是否爲正整數
- 28. 在C中檢查標準輸入#
- 29. 如何檢查加載時輸入是否爲空?
- 30. 檢查輸入和選擇是否爲空,並啓用按鈕
C++ or C?你的問題標有兩個。 – 2013-04-26 04:52:24
我不確定你的問題有明確的含義。想象一下* stdin *是一個管道(從一個需要年齡的命令中將其第一個字符吐出* stdout *)。你可以用'STDIN_FILENO'(即0)作爲文件描述符來調用[poll(2)](http://man7.org/linux/man-pages/man2/poll.2.html)。然後檢查* stdin *是否可讀...(即[read(2)](http://man7.org/linux/man-pages/man2/read.2.html)不會被阻止)。 – 2013-04-26 04:52:43