C语言查看文件大小的三种方法
C语言查看文件大小的三种方法
在C语言中,查看文件大小是一个常见的需求。本文将介绍三种方法:使用fseek和ftell、stat函数、fstat函数。其中,使用fseek和ftell是最常见的一种方法,因为它们是标准C库函数,易于理解和使用。
一、使用fseek和ftell函数
1. 打开文件
首先,我们需要使用fopen函数打开文件。fopen函数的原型如下:
FILE *fopen(const char *filename, const char *mode);
其中,filename是要打开的文件名,mode是打开文件的模式,如“r”表示以只读模式打开文件。
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return -1;
}
2. 移动文件指针
接下来,我们使用fseek函数将文件指针移动到文件末尾。fseek函数的原型如下:
int fseek(FILE *stream, long int offset, int whence);
其中,stream是文件指针,offset是相对于whence的位置偏移量,whence可以是SEEK_SET(文件开始)、SEEK_CUR(当前位置)、SEEK_END(文件末尾)之一。
fseek(file, 0, SEEK_END);
3. 获取文件大小
然后,我们使用ftell函数获取当前文件指针的位置,这个位置即为文件大小。ftell函数的原型如下:
long int ftell(FILE *stream);
long size = ftell(file);
printf("File size: %ld bytes\n", size);
4. 关闭文件
最后,我们使用fclose函数关闭文件。
fclose(file);
完整代码如下:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return -1;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
printf("File size: %ld bytes\n", size);
fclose(file);
return 0;
}
二、使用stat函数
stat函数是POSIX标准的一部分,可以用于获取文件的状态信息,包括文件大小。stat函数的原型如下:
int stat(const char *pathname, struct stat *statbuf);
其中,pathname是文件路径,statbuf是一个指向struct stat结构的指针,用于存储文件的状态信息。struct stat结构如下:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
};
获取文件状态信息
我们可以使用stat函数获取文件的状态信息,包括文件大小。
#include <sys/stat.h>
#include <stdio.h>
int main() {
struct stat st;
if (stat("example.txt", &st) == 0) {
printf("File size: %ld bytes\n", st.st_size);
} else {
perror("Failed to get file status");
}
return 0;
}
三、使用fstat函数
fstat函数与stat函数类似,不同之处在于fstat函数使用文件描述符而不是文件路径。fstat函数的原型如下:
int fstat(int fd, struct stat *statbuf);
其中,fd是文件描述符,statbuf是一个指向struct stat结构的指针,用于存储文件的状态信息。
获取文件描述符
首先,我们需要使用open函数打开文件,并获取文件描述符。open函数的原型如下:
int open(const char *pathname, int flags);
其中,pathname是文件路径,flags是打开文件的模式,如O_RDONLY表示以只读模式打开文件。
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Failed to open file");
return -1;
}
struct stat st;
if (fstat(fd, &st) == 0) {
printf("File size: %ld bytes\n", st.st_size);
} else {
perror("Failed to get file status");
}
close(fd);
return 0;
}
四、总结
C语言查看文件大小的几种方法包括使用fseek和ftell、stat函数、fstat函数。其中,使用fseek和ftell是最常见的一种方法,因为它们是标准C库函数,易于理解和使用。此外,stat和fstat函数也是查看文件大小的有效方法,尤其是在需要获取其他文件状态信息时。无论采用哪种方法,都需要注意正确打开和关闭文件,以避免资源泄漏。