Filesize
This commit is contained in:
parent
d7af70719c
commit
04220af434
1 changed files with 63 additions and 0 deletions
63
filesize.c
Normal file
63
filesize.c
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <sys/stat.h>
|
||||||
|
|
||||||
|
/* Different ways to get filesizes, some are linux-specific (i think), some are posix */
|
||||||
|
|
||||||
|
void file_tell(void);
|
||||||
|
void file_stat(void);
|
||||||
|
void file_end(void);
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
file_stat();
|
||||||
|
file_tell();
|
||||||
|
file_end();
|
||||||
|
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* This works on linux, but may not be posix compliant */
|
||||||
|
void file_stat(void) {
|
||||||
|
const char *filename = "filesize.c";
|
||||||
|
struct stat st;
|
||||||
|
|
||||||
|
if (stat(filename, &st) == 0) {
|
||||||
|
printf("File size: %lld bytes\n", (long long)st.st_size);
|
||||||
|
} else {
|
||||||
|
perror("stat");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* This works on all posix systems afaik */
|
||||||
|
void file_tell(void) {
|
||||||
|
FILE *f = fopen("filesize.c", "rb");
|
||||||
|
if (!f) {
|
||||||
|
perror("fopen");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
fseek(f, 0, SEEK_END);
|
||||||
|
long size = ftell(f);
|
||||||
|
fclose(f);
|
||||||
|
|
||||||
|
if (size >= 0) {
|
||||||
|
printf("File size: %ld bytes\n", size);
|
||||||
|
} else {
|
||||||
|
perror("ftell");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* This is bad for obvious reasons*/
|
||||||
|
void file_end(void) {
|
||||||
|
FILE *f = fopen("filesize.c", "rb");
|
||||||
|
if (!f)
|
||||||
|
return;
|
||||||
|
|
||||||
|
size_t size = 0;
|
||||||
|
while (fgetc(f) != EOF) {
|
||||||
|
size++;
|
||||||
|
}
|
||||||
|
fclose(f);
|
||||||
|
|
||||||
|
printf("File size: %zu bytes\n", size);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue