我有一些庫函數的麻煩。 我必須編寫一些C代碼,它使用庫函數在屏幕上打印其內部步驟。 我對它的返回值不感興趣,但只對打印的步驟感興趣。 所以,我認爲我必須從標準輸出讀取並將讀取的字符串複製到緩衝區中。 我已經嘗試過fscanf和dup2但是我無法從標準輸出中讀取。請幫幫我嗎?C語言。從標準輸出讀取
回答
我假設你的意思是標準輸入。另一個可能的功能是gets
,使用man gets
來了解它是如何工作的(非常簡單)。請出示您的代碼並解釋您失敗的位置以獲得更好的答案。
不,OP正在討論'stdout'。他有一個庫函數寫入'stdout',並且他想攔截那個輸出。 –
感謝大家。我使用了發佈的解決方案。有用! ;) – user2479368
好的,但仍然有一件事我不忍受。 爲什麼如果我想讀取書面文件,我不能? 我無法發佈代碼因爲8小時必須通過:S – user2479368
您應該能夠打開一個管道,DUP寫入結束到標準輸出,然後從管道的讀端讀,像下面,錯誤檢查:
int fds[2];
pipe(fds);
dup2(fds[1], stdout);
read(fds[0], buf, buf_sz);
好的,我用非純粹的解決方案修復了它。我用C++。 – user2479368
FILE *fp;
int stdout_bk;//is fd for stdout backup
stdout_bk = dup(fileno(stdout));
fp=fopen("temp.txt","w");//file out, after read from file
dup2(fileno(fp), fileno(stdout));
/* ... */
fflush(stdout);//flushall();
fclose(fp);
dup2(stdout_bk, fileno(stdout));//restore
以前的答案的擴展版本,沒有使用文件,並捕獲標準輸出的管道,而不是:
#include <stdio.h>
#include <unistd.h>
main()
{
int stdout_bk; //is fd for stdout backup
printf("this is before redirection\n");
stdout_bk = dup(fileno(stdout));
int pipefd[2];
pipe2(pipefd, 0); // O_NONBLOCK);
// What used to be stdout will now go to the pipe.
dup2(pipefd[1], fileno(stdout));
printf("this is printed much later!\n");
fflush(stdout);//flushall();
write(pipefd[1], "good-bye", 9); // null-terminated string!
close(pipefd[1]);
dup2(stdout_bk, fileno(stdout));//restore
printf("this is now\n");
char buf[101];
read(pipefd[0], buf, 100);
printf("got this from the pipe >>>%s<<<\n", buf);
}
生成以下的輸出:
this is before redirection
this is now
got this from the pipe >>>this is printed much later!
good-bye<<<
多麼真棒的答案! –
- 1. 寫入標準輸出並從標準輸入讀取C
- 2. C++從標準輸入和標準輸出讀取
- 3. VB.NET讀取標準輸出
- 4. 從gjs讀取異步標準輸出
- 5. WScript.Shell.Exec - 從標準輸出讀取
- 6. 從標準輸入讀取libxml2在C
- 7. 從標準輸入讀取C++
- 8. 從標準輸入讀取
- 9. 從標準輸入和輸出讀取到標準輸出是什麼意思?
- 10. 從C中的標準輸出讀取是可能的?
- 11. 如何從C#讀取PowerShell腳本標準輸出和標準錯誤#
- 12. 閱讀()從標準輸入讀取流
- 13. 從標準輸入讀取使用讀
- 14. C#與閱讀標準輸出問題
- 15. 如何逐行讀取標準輸出?
- 16. 從標準輸入讀取和打印到紅寶石標準輸出
- 17. 從標準輸出獲取輸出的系統命令C
- 18. 在C語言輸出中寫入和讀取CSV文件
- 19. 從標準輸入讀取數字行
- 20. Pylint:從標準輸入讀取?
- 21. 從標準輸入讀取,直到EOF
- 22. 從標準輸入流中讀取Hadoop
- 23. Haskell從標準輸入讀取文件
- 24. 從python的標準輸入讀取行?
- 25. 非阻塞從標準輸入讀取
- 26. 從標準輸入異步讀取
- 27. 從標準輸入讀取整數
- 28. 的wget從標準輸入讀取
- 29. 從標準輸入讀取密碼
- 30. netbeans從標準輸入讀取
顯示你試過的代碼,請!如果你製作了一個管道並正確使用了'dup2',你應該可以做你想做的事情。 –