开发者

file size in c program

I just want to find the file size with the help of c program..I wr开发者_Python百科ote a code but it give wrong result...

fseek(fp,0,SEEK_END);
osize=ftell(fp);

Is there any other way?


The stat system call is the usual solution to this problem. Or, in your particular case, fstat.


ftell returns an int. If you are on a system where int is 32 bits and your file is more than 2GB, you may very well end up with a negative size. POSIX provides ftello and fseeko which use a off_t. C has fgetpos and fsetpos which use a fpos_t -- but fpos_t is not an arithmetic type -- it keeps things related to the handling of charset by the locale for instance.


There is no reason why it should not work.

Is there any other way? You can use stat, if you know the filename:

struct stat st;
stat(filename, &st);
size = st.st_size;

By the way ftell returns a long int

The sys/stat.h header defines the structure of the data returned by the functions fstat(), lstat(), and stat().


Try using _filelength. It's not portable, though... I don't think there's any completely portable way to do this.


Try this using fstat():

int file=0;
if((file=open(<filename>,O_RDONLY)) < -1)
    return -1; // some error with open()

struct stat fileStat;
if(fstat(file,&fileStat) < 0)    
    return -1; // some error with fstat()

printf("File Size: %d bytes\n",fileStat.st_size);


The only negative return value by ftell is -1L if an error occurs. If you don't mind using WinAPI, get file size with GetFileSizeEx:

HANDLE hFile = CreateFile(filename, 
                          GENERIC_READ,
                          0, 
                          NULL,
                          OPEN_EXISTING, 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);

LARGE_INTEGER size;
GetFileSizeEx(hFile, &size);
printf("%ld", size.QuadPart);

CloseHandle(hFile);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜