Linux api文件io和 c库标准io 实现文本字节数计算
linux api实现
代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int readFileSize_API(const char *pathname, int *fileSize);
int main(int argc, char *argv[])
{
int fileSize = 0;
if(2 != argc){
printf("usage: format like \" argv[0] pathname\".\n");
exit(EXIT_FAILURE);
}
if(!readFileSize_API(argv[1], &fileSize)){
printf("文件 %s 的大小为:%d字节.\n", argv[1], fileSize);
}
return 0;
}
int readFileSize_API(const char *pathname, int *fileSize)
{
int fd = -1;
int size;
fd = open(pathname, O_RDONLY);
if(-1 == fd){
printf("func:%s line:%d\n",__func__,__LINE__);
fflush(stdout);
perror("error");
return -1;
}
size = lseek(fd, 0, SEEK_END);
close(fd);
*fileSize = size;
return 0;
}
结果示例:
# ./a.out a.out
文件 a.out 的大小为:7697字节.
标准IO实现
代码
#include <stdio.h>
#include <stdlib.h>
int readFileSize_Stdio(const char *pathname, int *fileSize);
int main(int argc, char *argv[])
{
int fileSize = 0;
if(2 != argc){
printf("usage: format like \" argv[0] pathname\".\n");
exit(EXIT_FAILURE);
}
if(!readFileSize_Stdio(argv[1], &fileSize)){
printf("文件 %s 的大小为:%d字节.\n", argv[1], fileSize);
}
return 0;
}
int readFileSize_Stdio(const char *pathname, int *fileSize)
{
FILE *fd = NULL;
int size;
fd = fopen(pathname, "rb"); //以二进制流打开
if(NULL == fd){
printf("func:%s line:%d\n",__func__,__LINE__);
fflush(stdout);
perror("error");
return -1;
}
fseek(fd, 0, SEEK_END);
size = ftell(fd);
close(fd);
*fileSize = size;
return 0;
}
结果与api实现相同。