[英]C90 printf with \n or \r\n not working in cygwin; but fflush(stdout); works fine. why?
Cygwin64位
編譯命令:
gcc hello.c -o hello -ansi -pedantic-errors
運行命令
./hello
你好ç
#include<stdio.h>
int main() {
/*setbuf(stdout, 0); I KNOW THIS WILL WORK IF ADDED, it is a solution, but I want to know why line break itself is not working*/
printf("hello world!\n");
printf("hello world again!\r\n");
/*fflush(stdout); without fflush, the above strings are not showing*/
while(1)
{
}
}
問題:
我不想在每個printf之后出現錯誤,以使終端及時顯示字符串,那又如何呢?
解答:setbuf(stdout,0);
考慮到很多帖子指出換行符可以解決此問題,為什么在我的情況下“ \\ n”或“ \\ r \\ n”不起作用?
cygwin的終端的行為與正常的Linux終端是否不同? 由於我沒有安裝Linux,因此有人可以為我進行測試嗎?
還是讓我問一個更籠統的問題:在哪種類型的終端上,“換行會強制沖洗”這句話是正確的?
謝謝
似乎在Cygwin中, stdout
不被標識為終端(而是管道),因此默認情況下它不是行緩沖的。
基於此答案 ,也許與Cygwin DLL鏈接會有所幫助。
我對cgywin一無所知。 但是這里我在Linux上進行了測試。
我嘗試下面的代碼,並通過編譯:gcc -std = c90 filename.c
不使用fflush它在循環之前打印所有單詞,所以我認為換行符會刷新緩沖區! 就是這樣!
我使用SUSE gcc。
#include<stdio.h>
int main() {
/*setbuf(stdout, 0); I KNOW THIS WILL WORK IF ADDED, it is a solution, but I want to know why line break itself is not working*/
printf("hello world!\n"); /*without fflush, not shown*/
printf("hello world again!\r\n"); /*without fflush, not shown*/
/* fflush(stdout);*/
while(1)
{
}
}
該程序在32位Cygwin下對我有效。 具體來說,當我編譯並執行此程序時:
#include<stdio.h>
int main() {
/*setbuf(stdout, 0); I KNOW THIS WILL WORK IF ADDED, it is a solution, but I want to know why line break itself is not working*/
printf("hello world!\n");
printf("hello world again!\r\n");
/*fflush(stdout); without fflush, the above strings are not showing*/
while(1)
{
}
}
它產生以下輸出:
hello world!
hello world again!
然后掛起,直到用Ctrl-C殺死它為止。
在Windows控制台,minty和xterm下從bash調用程序時,我得到了相同的行為(我懷疑終端是否會有所作為)。
我使用的是64位Windows 7下的32位Cygwin。您說的是幾天前才宣布的 64位Cygwin。 我還沒有嘗試過。
我懷疑64位與32位Cygwin存在問題。 我建議您張貼到Cygwin郵件列表 。
這是您程序的清理版本,應顯示相同的問題(請確保注釋正確):
#include <stdio.h>
int main(void) {
/* Adding setbuf(stdout, 0) here makes the output appear */
printf("hello world!\n");
/* Adding fflush(stdout) here makes the output appear */
while(1) {
/* nothing */
}
}
我剛遇到這個問題。 我已經使用了一段時間的代碼,不得不在PC上重新安裝Cygwin。 這次我安裝了64位版本,以前是x86。
構建我的代碼,在bash shell中運行它,沒有輸出。
我沒有意識到的是,我的bin文件夾中仍然有以前的cygwin 32位版本的Cygwin1.dll。 我將其重命名並運行了程序,輸出結果正常。
您可能有其他問題,但是如果您在使用bin其他文件夾中使用了不同的dll版本,則可能會導致此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.