Linux使用c语言获取文件大小
时间: 2024-11-21 16:09:10 浏览: 28
在Linux环境下,使用C语言获取文件大小通常通过系统调用`fstat()`函数完成。这个函数可以从文件描述符获取文件的状态信息,包括文件大小。以下是基本步骤:
1. 首先,打开你需要获取大小的文件,获取一个对应的文件描述符(file descriptor),比如通过`open()`函数。
```c
int fd = open("filename", O_RDONLY); // 读取模式
```
2. 然后,使用`fstat()`函数传入文件描述符和一个`struct stat`结构体,该结构体将接收文件的信息,包括大小。
```c
struct stat file_stat;
if (fstat(fd, &file_stat) != 0) {
perror("Failed to get file stats");
exit(EXIT_FAILURE);
}
```
3. 文件大小存储在`file_stat.st_size`字段中,单位通常是字节。
```c
off_t fileSize = file_stat.st_size;
```
4. 关闭文件描述符,释放资源。
```c
close(fd);
```
完整的示例代码如下:
```c
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s filename\n", argv[0]);
return -1;
}
char* filename = argv[1];
int fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return -1;
}
struct stat fileStat;
if (fstat(fd, &fileStat) != 0) {
perror("Failed to get file stats");
close(fd);
return -1;
}
off_t fileSize = fileStat.st_size;
printf("File size: %lld bytes\n", fileSize);
close(fd);
return 0;
}
```
阅读全文
相关推荐

















