1、使用 fseek() 和 ftell()
获取文件大小的标准方法。可以将文件指针移到文件的末尾,然后使用 ftell()
获取当前位置的偏移量(即文件的大小)。
#include <stdio.h>
long get_file_size(const char *filename) {
FILE *file = fopen(filename, "rb");
if (file == NULL) {
perror("Error opening file");
return -1;
}
// 将文件指针移动到文件末尾
fseek(file, 0, SEEK_END);
// 使用 ftell 获取文件大小
long size = ftell(file);
// 关闭文件
fclose(file);
return size;
}
int main() {
const char *filename = "example.txt";
long size = get_file_size(filename);
if (size != -1) {
printf("File size: %ld bytes\n", size);
}
return 0;
}
2、使用 stat() 函数
另一个获取文件大小的方法是使用 stat()
函数,它提供了文件的详细信息,包括文件大小。
#include <stdio.h>
#include <sys/stat.h>
long get_file_size(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0) {
return st.st_size;
} else {
perror("Error getting file size");
return -1;
}
}
int main() {
const char *filename = "example.txt";
long size = get_file_size(filename);
if (size != -1) {
printf("File size: %ld bytes\n", size);
}
return 0;
}
3、使用 fstat() 函数
fstat()
是另一个可以获取文件大小的函数。它与 stat()
类似,但是它接受文件描述符作为参数,而不是文件名。
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
long get_file_size(const char *filename) {
int fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return -1;
}
struct stat st;
if (fstat(fd, &st) == 0) {
close(fd);
return st.st_size;
} else {
perror("Error getting file size");
close(fd);
return -1;
}
}
int main() {
const char *filename = "example.txt";
long size = get_file_size(filename);
if (size != -1) {
printf("File size: %ld bytes\n", size);
}
return 0;
}