试图了解ftell函数的返回值

时间:2014-01-14 09:25:03

标签: c linux gcc file-io seek

#include<stdio.h>
#include<string.h>

int main()
{
   long int count; 
   FILE *file=NULL;

   file=fopen("sample.txt","r+");
   if(file==NULL)
   {
      printf("file open fail\n");
      return;
   }
   printf("file open succesfull\n");

   if(0!=fseek(file,1,SEEK_END))
   {
      printf("seek failed\n");
      return;
   }
   printf("seek successful\n");

   count=ftell(file);

   printf("%lu", count);

   return 0;
}

输出

file open succesfull
seek successful
3

我的smaple.txt文件只有一个char,那就是q。为什么它在这里显示3? 此外,当我将文件清空时,ftell()返回1,那是什么?
在ubuntu 12.04上工作

3 个答案:

答案 0 :(得分:4)

您的fseek(file, 1, SEEK_END)将位置超出的位置放在文件的末尾。这就解释了为什么您将count视为空文件的原因。我猜你的文件,只包含一个q,也包含一个回车,实际上包含两个字符。最后的角色是3,你观察到的。

答案 1 :(得分:2)

您错误地使用fseek()来通过ftell()确定文件的大小。

来自我man fseek()斜体):

  

int fseek(FILE * stream,long offset,int whence);

     

[...]以字节为单位的新位置是          通过将偏移字节添加到由whence 指定的位置来获取

这一行:

if(0!=fseek(file,1,SEEK_END))

在文件末尾之后将文件指针1字节定位。

要解决此问题,请执行以下操作:

if (0 != fseek(file, 0, SEEK_END))

答案 2 :(得分:0)

你误解了ftell&amp; fseek功能。少喝咖啡休息:p

ftell manpage

  

long ftell(FILE * stream);

     

ftell()函数获取文件位置的当前值   流指向的流的指示符。

fseek manpage

  

int fseek(FILE * stream,long offset,int whence);

     

fseek()函数设置流的文件位置指示符   流指出。以字节为单位的新位置是   通过将偏移字节添加到位置spec-获得          如果是的话。如果whence设置为SEEK_SET,SEEK_CUR或SEEK_END,则偏移量相对于文件的开头,当前   位置指示符或文件结尾。一个          成功调用fseek()函数会清除流的文件结束指示符并撤消ungetc的任何效果(3)   在同一个流上运行。

创建sample.txt

  

echo -n'q'&gt; sample.txt的

文件搜寻示例

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

int main( int argc, char** argv )
{
    FILE* file = fopen( "sample.txt", "r" );

    if( NULL == file )
    {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }

    printf("File successfully opened\n");

    long position = ftell( file );

    printf( "Position before seek: %lu\n", position );

    int status = fseek( file, 1L, SEEK_SET );

    if( 0 != status )
    {
         perror("Failed to seek");
         return EXIT_FAILURE;
    }

    printf("File seek successful\n");

    position = ftell( file );

    printf( "Position after seek: %lu\n", position );

    return EXIT_SUCCESS;
}

文件大小示例

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main( int argc, char** argv )
{
    struct stat file_status = { 0 };

    int status = stat( "sample.txt", &file_status );

    if ( 0 != status )
    {
        perror("Failed to read file status");
        return EXIT_FAILURE;
    }

    printf( "File size: %li\n", file_status.st_size );

    return EXIT_SUCCESS;
}

<强>构建

  

gcc -o example example.c