在 C 语言中,可以使用标准库函数 fseek() 和 ftell() 来获取文件的大小。具体步骤如下:
1.打开文件,并判断文件是否成功打开。
2.将文件指针移动到文件末尾处。
3.通过 ftell() 函数获取文件指针当前位置相对于文件起始位置的偏移量,即为文件大小。
4.关闭文件。
下面是一个示例代码:
#include <stdio.h>
long getFileSize(FILE* file) {
long fileSize = -1;
if (file != NULL) {
if (fseek(file, 0L, SEEK_END) == 0) {
fileSize = ftell(file);
}
rewind(file);
}
return fileSize;
}
int main() {
FILE* file;
long size;
file = fopen("example.txt", "rb");
if (file == NULL) {
printf("Failed to open file.\n");
return -1;
}
size = getFileSize(file);
if (size != -1) {
printf("File size: %ld bytes\n", size);
} else {
printf("Failed to get file size.\n");
}
fclose(file);
file = NULL;
return 0;
}
这个程序会输出包含文件大小的一条消息,或者在获取文件大小失败时,输出错误消息。
需要注意的是,对于非常大的文件,ftell() 函数返回的值可能会超出 long 类型能够表示的范围,因此需要使用其它方式来获取文件大小。