c 文件处理:25 年后无法写入?

c file handling : unable to write after 25 y?

#include<stdio.h>

main()
{
    FILE *p,*q;
    char b;
    int a;
    p = fopen("three", "w");
    for(a=1; a<=50; a++)
        fprintf(p, "%c", a);
    fclose(p);

    q = fopen("three", "r");
    while(!feof(q))
    {
        fscanf(q, "%c", &b); //dont print after 25! ?
        printf("%d",b);
    }
    fclose(q);
}

问题是为什么它在 25 之后不打印。我也尝试删除 feof 但它显示只有第 25 个字符被读取到文件中。 我猜这条线造成了一些问题!

fprintf(p,"%c",26);

但不知道为什么!

失败的原因有两个。如果您的系统默认以文本模式打开文件,它将响应控制字符。所以你必须以 binary 模式打开文件:

p = fopen("three", "wb");
...
q = fopen("three", "rb");

第二个失败是使用了没用的feof()。当您到达文件末尾时它不会通知,但只有 之后您在文件末尾进行了错误的读取。这就是 25 或更正后的 50 被打印两次的原因。

Here is feof() link.

这显示了有效的方法

#include<stdio.h>

int main()                              // main needs a return type
{
    FILE *p,*q;
    char b;
    int a;
    p = fopen("three", "wb");           // binary mode
    if (p == NULL)                      // test file open
        return 1;
    for(a=1; a<=50; a++)
        fprintf(p, "%c", a);
    fclose(p);

    q = fopen("three", "rb");           // binary mode
    if (q == NULL)                      // test file open
        return 1;
    while (1 == fscanf(q, "%c", &b))    // test the read result
        printf("%d ",b);
    fclose(q);
    return 0;
}

程序输出

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

我是这样写的,测试了代码。

注意主函数声明的更正

注意在末尾添加 return 语句

注意,仅用于输出格式化,printf

的格式字符串

printf 格式字符串中的 '\n' 导致立即刷新输出缓冲区。

注意在两个 fopen 语句之后添加了错误检查

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

int main( void )
{
    FILE *p,*q;
    char b;
    int a;
    if( NULL == ( p = fopen("three", "w") ) )
    { // then fopen failed
        perror( "fopen for write: three failed" );
        exit( EXIT_FAILURE );
    }

    // implied else,  fopen successful

    for(a=1; a<=50; a++)
        fprintf(p, "%c", a);
    fclose(p);

    if( NULL == (q = fopen("three", "r") ) )
    { // then fopen failed
        perror( "fopen for read: three failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    while(1 == fscanf(q, "%c", &b) ) //dont print after 25! ?
    {
        printf("%d\n",b);
    }
    fclose(q);

    return(0);
}