Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Trying to understand the return value of ftell function
#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;
}

Output

file open succesfull
seek successful
3

My smaple.txt file has only one char and that is q. Why it is showing 3 here ? Also when I am having the file empty, then ftell() is returning 1, what is that?
Working on ubuntu 12.04

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Your fseek(file, 1, SEEK_END) places the position one character beyond the end of the file. That explains why you observe count as one for the empty file. I guess that your file, that contains just a q, also contains a carriage return consisting of actually two characters. On character behind the end is 3, what you observed.

over 4 years ago · Santiago Trujillo Relatório

0

You use fseek() incorrectly to determine the file's size via ftell().

From man fseek() (italics by me):

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

[...] The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence.

This line:

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

positions the file pointer 1 byte after the end of the file.

To fix this do:

if (0 != fseek(file, 0, SEEK_END))
over 4 years ago · Santiago Trujillo Relatório

0

You have misinterpreted the ftell & fseek functions. Less coffee more rest :p

ftell manpage

long ftell(FILE *stream);

The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.

fseek manpage

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

The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position spec‐ ified by whence. If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function on the same stream.

Create sample.txt

echo -n 'q' > sample.txt

File Seek Example

#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;
}

File Size Example

#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;
}

Build

gcc -o example example.c

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda