【问题标题】:can't find what's wrong with the function fseek()找不到函数 fseek() 有什么问题
【发布时间】:2015-05-08 23:50:56
【问题描述】:

我写了这段代码,似乎函数 fseek() 有问题。因为它会影响从文本文件中读取。它使函数 fscanf() 从文件中读取垃圾和错误数据之类的东西。我的文件只包含浮点数。

FILE *fptr;
if ( !( fptr = fopen( "saving.txt", "r" ))){
    printf( "File could not be opened to retrieve your data from it.\n" );
}
else {
    fseek(fptr, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(fptr);
    if (len > 0) {  //check if the file is not empty.
        while ( !feof( fptr ) ){
            fscanf( fptr,"%f\n", &p.burst_time );
            //printf("time = %f\n",p.burst_time);
            AddProcess(&l,p.burst_time);
        }
    }
    fclose( fptr );
}

提示:这部分代码用于判断文件是否为空。如果不从中读取。我还使用函数 rewind(fptr);在循环之前,但没有区别。提前致谢。

【问题讨论】:

  • 你需要测试fscanf()的返回值,看看它是否读到了什么。
  • 如果您首先查找文件末尾,为什么您期望能够读取任何内容?那里什么都没有!
  • 你忘了回到循环之前的开头吗?
  • 我也用rewind(fptr);在循环之前,但没有区别,它不会读取它读取的任何内容,而是像垃圾一样的大量数字。

标签: c


【解决方案1】:

只看一段代码:

fseek(fptr, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(fptr);
if (len > 0) {  //check if the file is not empty.
    while ( !feof( fptr ) ){
        fscanf( fptr,"%f\n", &p.burst_time );

由于某种原因,您在进行任何读取之前都在寻找文件的末尾。我假设您这样做是为了计算文件的大小。

你得到疯狂输出的原因是你实际上没有读过任何东西,所以feof直到第一次通过才返回文件结尾。

我建议您通过在 while 语句之前添加 fseek(fptr, 0, SEEK_SET); 来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多