簡體   English   中英

getc 與 Windows 與 Unix

[英]getc with Windows vs Unix

我對以下代碼有疑問:

while((c = getc(pFile)) != EOF)
{
    if(c != '\n')
    {
         input[index] = (char)c;
         index++;
     } else
     {
         input[index] = '\0';
         index = 0;
     }
}

在 Windows 中,此 c = getc 行讀取 '\n'(代碼 10)兩次。 例如,我正在使用以下 2 行讀取文件:

Hello world
Test

c = getc 讀取 Hello world,但再次讀取 10 (\n) 和 10,將輸入數組重置為空白(因為 '\0')。 在 unix 中,'\n' 只被讀取一次,所以一切正常。

任何想法?

提前致謝。

兩個平台上的文件在物理上是否相同,即逐位? 這是自找麻煩,因為行尾的編碼不同。

Windows 用\r\n終止行。 這可能會有所幫助:

$ echo test | unix2dos > /tmp/test
$ hexdump -c /tmp/test
0000000   t   e   s   t  \r  \n                                        
0000006

奇怪的\r值是 13,所以我不知道 wath 出了什么問題。

嘗試這個:

while((c = getc(pFile)) != EOF)
{
    if(c != '\n' && index)
    {
         input[index] = (char)c;
         index++;
    } 
    else
    {
         if (!index)
              continue; // dumps repeated '\n'

         input[index] = '\0';
         index = 0;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM