C语言中的意外文件指针遍历行为

时间:2016-04-18 18:34:24

标签: c file pointers text-files

这是我的代码 -

#include<stdio.h>
void main()
{
    FILE *fp;
    fp=fopen("ex.c","w+");
    fputs("Hello World\nFile Pointer",fp);
    printf("Text - \n");
    rewind(fp);
    char ch;
    while((ch=fgetc(fp))!=EOF)
    {
        printf("File pointer  - %d and letter - ",ftell(fp));
        if(ch=='\t')
            printf("tab");
        else
        if(ch=='\n')
            printf("newline");
        else
            putchar(ch);
        printf("\n");
    }
}

这是我得到的输出 -

Text -
File pointer  - 1 and letter - H
File pointer  - 2 and letter - e
File pointer  - 3 and letter - l
File pointer  - 4 and letter - l
File pointer  - 5 and letter - o
File pointer  - 6 and letter -
File pointer  - 7 and letter - W
File pointer  - 8 and letter - o
File pointer  - 9 and letter - r
File pointer  - 10 and letter - l
File pointer  - 11 and letter - d
File pointer  - 13 and letter - newline
File pointer  - 14 and letter - F
File pointer  - 15 and letter - i
File pointer  - 16 and letter - l
File pointer  - 17 and letter - e
File pointer  - 18 and letter -
File pointer  - 19 and letter - P
File pointer  - 20 and letter - o
File pointer  - 21 and letter - i
File pointer  - 22 and letter - n
File pointer  - 23 and letter - t
File pointer  - 24 and letter - e
File pointer  - 25 and letter - r

但我期待的是 -

Text -
File pointer  - 1 and letter - H
File pointer  - 2 and letter - e
File pointer  - 3 and letter - l
File pointer  - 4 and letter - l
File pointer  - 5 and letter - o
File pointer  - 6 and letter -
File pointer  - 7 and letter - W
File pointer  - 8 and letter - o
File pointer  - 9 and letter - r
File pointer  - 10 and letter - l
File pointer  - 11 and letter - d
File pointer  - 12 and letter - newline
File pointer  - 13 and letter - F
File pointer  - 14 and letter - i
File pointer  - 15 and letter - l
File pointer  - 16 and letter - e
File pointer  - 17 and letter -
File pointer  - 18 and letter - P
File pointer  - 19 and letter - o
File pointer  - 20 and letter - i
File pointer  - 21 and letter - n
File pointer  - 22 and letter - t
File pointer  - 23 and letter - e
File pointer  - 24 and letter - r

它所说的一个特定行 -

 File pointer  - 13 and letter - newline

我没想到文件指针值从11跳到13,但是期待它从11变为12。
这种行为背后的原因是什么?

但是当我在代码中更改此行时 - fputs("Hello World\nFile Pointer",fp);

到 - fputs("Hello World\tFile Pointer",fp);

我得到了我预期的输出。
为什么会这样?

1 个答案:

答案 0 :(得分:0)

您必须在Windows上运行它,它使用DOS格式的文本文件。在此格式中,换行符在文件中表示为两个字节:Carriage Return后跟Line Feed。所以它必须从文件中读取2个字节来读取单个&#34;换行符&#34;字符,这反映在ftell()返回的偏移量中。

如果您在Unix上运行该程序,您将得到您期望的结果,因为它仅使用Line Feed作为换行符。