首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

fscanf函数读入错误

2013-09-06 
fscanf函数读入异常#include stdio.hint main(){FILE* fileint a,bfile fopen( test.txt, w+)f

fscanf函数读入异常

#include <stdio.h>

int main()
{

    FILE* file;
    int a,b;
    file = fopen( "test.txt", "w+");
    fprintf (file, "%d %d",8,9);
    fscanf (file, "%d", &a);
    fscanf (file, "%d", &b);
    printf ("%d %d", a, b);
    fclose (file);
    return 0;
}


文件中已读入“8 9”,但程序输出为50 4534376,这是怎么回事? fscanf
[解决办法]
你写入数据后没关闭文件,文件指针在你写入数据的后面,你再去读文件,当然会出错

你写入文件后先关闭,再去读,或者 fseek(file,0,SEEK_SET)在去读
[解决办法]

#include <stdio.h>
 
int main()
{
 
    FILE* file;
    int a,b;
    file = fopen( "test.txt", "w+");
    fprintf (file, "%d %d",8,9);
    fseek(file,0,SEEK_SET);    //这个文件指针置零。
    fscanf (file, "%d", &a);
    fscanf (file, "%d", &b);
    printf ("%d %d", a, b);
    fclose (file);
    return 0;
}

哈哈,如楼上所示啊
[解决办法]
引用:

#include <stdio.h>
 
int main()
{
 
    FILE* file;
    int a,b;
    file = fopen( "test.txt", "w+");
    fprintf (file, "%d %d",8,9);
    fseek(file,0,SEEK_SET);    //这个文件指针置零。
    fscanf (file, "%d", &a);
    fscanf (file, "%d", &b);


    printf ("%d %d", a, b);
    fclose (file);
    return 0;
}


哈哈,如楼上所示啊

    fseek(file,0,SEEK_SET);    //这个文件指针置零。
这个注释是错误的!
尽管是通过file这个文件指针去操作,但决不是将这个文件指针置零!
fseek这个函数是通过文件指针去设置读写位置(有的书上把它叫做文件读写位置指针----但它不是我们在C中用的“指针”,而是读写字符或其它对象时的位置序号)。
我们可以这样测试,在fseek函数后输出file指针的值,看看它是零吗?

热点排行