Name: Anonymous 2009-04-17 4:56
Whats the most crossplatform way to get file length in C?
FILE *f;
long len;
f = fopen("file", "r");
fseek(f, 0, SEEK_END);
len = ftell(f);
fclose(f);fstat() is POSIX and is more or less uniform across GNU/Linux, *BSD and Solaris (on Solaris struct elements are in wrong order but have standard names), however I'm not sure how it will behave on real operating systems like Windows 9x, Plan 9 and I-TRON.
stat is more portable than fstat.
System.Unsafe.unsafeGetFileLength
Prelude> System.Unsafe.unsafeGetFileLength "test.hs"
Error: stack overflow
Prelude> :?
Error: stack overflow
Prelude>
Error: stack overflow
PrErErroeluder: ror: stacstack >overflowk overflow
% ghci
GHCi, version 6.10.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ..
Error: stack overflow
%
Prelude> error "stack overflow"
*** Exception: stack overflow
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\James>ghci
GHCi, version 6.10.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> in c major
<interactive>:1:0: parse error on input `in'
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\James>ghci
GHCi, version 6.10.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> in c major
*** Exception: stack overflow
[0593][haxus:~] ghci
GHCi, version 6.8.2: http://www.haskell.org/ghc/ :ihbt for help
Loading package base ... linking ... done.
Prelude> :q
*** Exception: stack overflow
#include <stdio.h>
#include <stdlib.h>
int filesize(char *);
int main(int argc, char *argv[]) {
int s;
if(argc < 2) {
printf("%s <filnamn>\n", argv[0]);
exit(-1);
}
if((s = filesize(argv[1])) != -1) {
printf("%s: %d bytes\n", argv[1], s);
} else {
printf("Kunde inte \xf6ppna %s!\n", argv[1]);
}
exit(0);
}
int filesize(char *fil) {
int storlek;
FILE *fp;
int start, slut;
if((fp = fopen(fil, "r")) != NULL) {
fseek(fp, 0, SEEK_SET);
start = ftell(fp);
fseek(fp, 0, SEEK_END);
slut = ftell(fp);
rewind(fp);
storlek = slut-start;
return(storlek);
}
return(-1);
}
"GRUNNUR"