-2

Possible Duplicate:
How do you determine the size of a file in C?

How can I obtain a file's size in C? I opened with an application written in C. I would like to know the size, because I want to put the content of the loaded file into a string, which I alloc using malloc(). Just writing malloc(10000*sizeof(char)

Community
  • 1
  • 1
EricDai
  • 25
  • 3

5 Answers5

3

You can use the fseek and ftell functions:

FILE* f = fopen("try.txt","rb");
fseek(f, 0, SEEK_END);
printf("size of the file is %ld", ftell(f));
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

for file size, stat, lstat or fstat will be the right choice.

pleas check stat

agfe2
  • 492
  • 7
  • 15
0
    int Get_Size( string path )
{

FILE *pFile = NULL;

// get the file stream

fopen_s( &pFile, path.c_str(), "rb" );


// set the file pointer to end of file

fseek( pFile, 0, SEEK_END );

// get the file size

int Size = ftell( pFile );

// return the file pointer to begin of file if you want to read it

rewind( pFile );

// close stream and release buffer

fclose( pFile );

return Size;
}

more answers cplusplus.com

CosminO
  • 5,018
  • 6
  • 28
  • 50
0

You can position yourself at the end of the file with fseek and use ftell() for that:

FILE *fd;
fd = fopen("filename.txt","rb");
fseek ( fd, 0 , SEEK_END );
int fileSize = ftell(fd);

filesize will contain the size in Bytes.

gekod

Helder AC
  • 376
  • 1
  • 5
  • 17
0

I thought there was a standard C function for this, but I couldn't find it.

If your file size is limited, you can use the solution proposed by izomorphius.

If your file can be larger than 2GB then you can use the _filelengthi64 function (see http://msdn.microsoft.com/en-us/library/dfbc2kec(v=vs.80).aspx). Unfortunately, this is a Microsoft/Windows function so it's probably not available for other platforms (although you will probably find similar functions on other platforms).

EDIT: Look at afge2's answer for the standard C function. Unfortunately, I think this is still limited to 2GB.

Patrick
  • 23,217
  • 12
  • 67
  • 130