_Filelength and chsize problems

I have an exmpl.cpp file that contains the following code (from here ):

#include <sys/io.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> 
#include <stdio.h>

void main( void )
{
   int fh, result;
   unsigned int nbytes = BUFSIZ;

   /* Open a file */
   if( (fh = open( "data", O_RDWR | O_CREAT, S_IREAD
                   | S_IWRITE ))  != -1 )
   {
      printf( "File length before: %ld\n", filelength( fh ) );
      if( ( result = chsize( fh, 329678 ) ) == 0 )
         printf( "Size successfully changed\n" );
      else
         printf( "Problem in changing the size\n" );
      printf( "File length after:  %ld\n", _filelength( fh ) );
      close( fh );
   }
}

      

Try to compile it with g++ exmpl.cpp -o exmpl

and get this:

exmpl.cpp: 18: 60: error: '_filelength was not declared in this scope exmpl.cpp: 19: 43: error:' chsize was not declared in this scope

Are there alternative functions like these functions?

Many thanks.

+3


source to share


1 answer


The problem is that it _filelength

is only a Windows function.

On Linux / Mac, you can use stat

to solve the problem:



#include <sys/stat.h>

long file_length(char *f)
{
    struct stat st;
    stat(f, &st);
    return st.st_size;
}

      

About resizing a file. The function is chsize

also not Linux, but you can use it ftruncate

to get the job done.

+2


source







All Articles