[英]Why cursor goes to next line while printing a file of one line?
我有下面的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確認了這一點(但是,我仍然不明白為什么wc給出的字符數是24個而不是23個)。
下面是該程序的輸出。
-bash-4.1$ ./a.out
It starts with the end.
Number of characters in this file: 24
-bash-4.1$
您可以看到,在打印了文件的所有字符之后,即使我在打印了文件的所有字符之后注釋了printf(“ \\ n”),光標也會移到下一行。
為什么將光標移到新行? 我期望在打印文件的所有字符后光標位於同一行,因此在下一個printf中使用了\\ t。
還可以看到我的程序說的字符數是24(與“ wc poem.txt”輸出內聯)。
所以我很困惑為什么在打印文件的最后一個字符后光標會移到新行? 還有為什么總字符數(noc)為24而不是23?
PS盡管我對“ wc”顯示的字符數有相同的疑問,但可以忽略“ wc”輸出,但if行數除外。 我可能會為此發布下一個問題。
謝謝。
為什么將光標移到新行?
'\\n'
字符。 還可以看到我的程序說的字符數是24(與“ wc poem.txt”輸出內聯)。
'\\n'
都在文件中。 您可以嘗試轉義空格字符以查看它們,因為它們是不可見的,因此類似這樣
while ((ch = fgetc(fp)) != EOF)
{
noc++;
if (isspace(ch) != 0)
printf("\\%02X", ch);
else
printf("%c", ch);
}
這樣,您將看到每個字符,您需要包含<ctype.h>
注意 :僅在非常特殊的情況下才需要使用break
恕我直言,我不喜歡它,因為它很難遵循程序流程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.