为什么在打印一行文件时光标会转到下一行?

时间:2015-02-14 23:33:55

标签: c file io cursor printf

我在C程序下方打印文件内容并计算其中的总字符数。

#include<stdio.h>
#include<stdlib.h>

int main()
{
    /*Declaring a FILE pointer fp.*/
    FILE *fp;
    char ch;
    int noc = 0;

    /*Using fopen() to get the address of the FILE structure, and store it in fp*/
    fp = fopen("poem.txt","r");
    if (fp == NULL)
    {
            printf("Error opening file");
            exit(1);
    }
    while(1)
    {
            ch = fgetc(fp);
            if (ch == EOF) /* EOF will be there at the end of the file.*/
                    break;
            noc++;
            printf("%c",ch); /* Printing the content of the file character by character*/
    }

    //printf("\n");

    close(fp); /* We need to fclose() the fp, because we have fopen()ed */

    printf("\tNumber of characters: %d\n",noc);

    return 0;
}

/*One interesting observation: There is an extra new line printed. Why ???*/

文件poem.txt只有一行。以下是poem.txt的内容

从结束开始。

我在编写此文件时没有按ENTER键,因此它只有一行。

-bash-4.1$ wc poem.txt
 1  5 24 poem.txt
-bash-4.1$

你可以看到这是由wc确认的(Howevr我仍然不明白为什么wc给出的字符数为24,而不是23)。

以下是该程序的输出。

-bash-4.1$ ./a.out
It starts with the end.
     Number of characters in this file: 24
-bash-4.1$

你可以看到,在打印完文件的所有字符后,即使我在打印文件的所有字符后注释了printf(&#34; \ n&#34;),光标也会被带到下一行。

为什么光标被带到新线?我打算在打印文件的所有字符后光标位于同一行,因此在下一个printf中使用\ t。

你也看到我的程序说字符数是24(与#34; wc poem.txt&#34;输出内联)。

所以我很困惑为什么在打印文件的最后一个字符后光标被带到新行?另外,为什么总字符数(noc)为24而不是23?

P.S。虽然我对&#34; wc&#34;所显示的字符数有同样的疑问。你可以忽略&#34; wc&#34; outout除了行号以外的数字。我可能会发布下一个问题。

感谢。

1 个答案:

答案 0 :(得分:2)

  

为什么光标被带到新线?

  • 因为'\n'字符在文件中。
  

你也看到我的程序说字符数是24(与“wc poem.txt”输出内联)。

  • 因为打印的23个字符加上'\n'都在文件中。

您可以尝试转义空格字符以查看它们,因为它们是不可见的,所以像这样

while ((ch = fgetc(fp)) != EOF)
{
    noc++;
    if (isspace(ch) != 0)
        printf("\\%02X", ch);
    else
        printf("%c", ch);
}
通过这种方式,您将看到每个角色,您需要包含<ctype.h>

注意:使用break只是在非常特殊的情况下需要IMHO,我不喜欢它,因为它很难跟上程序流程。

相关问题