1. 程式人生 > >嵌入式Linux標準IO,獲取檔案大小fgetc(),定位流獲取檔案大小fteel()、rewind()/fseek(),處理錯誤資訊perror()/strerror()

嵌入式Linux標準IO,獲取檔案大小fgetc(),定位流獲取檔案大小fteel()、rewind()/fseek(),處理錯誤資訊perror()/strerror()

#include <stdio.h>
#include <errno.h>
#include <string.h>

int get_file_size(const char *file);
int main(int argc, const char *argv[])
{
	if(argc < 2)
	{
		printf("no file name or path\n");
		return -1;
	}
	else
	{
		printf("total %d bytes\n",get_file_size(argv[1]));
	}


	return
0; }

1、fgetc()獲取檔案大小

int get_file_size(const char *file)
{
	int count=0;
	FILE *fp;
	if((fp = fopen(file,"r")) == NULL)
	{
		perror("fopen");
		//printf("fopen:%s\n",strerror(errno));//errno-----<errno.h>,strerror()------<string.h>
		return -1;
	}
	
	while(fgetc(fp) != EOF)
	{
		count ++
; } if((fclose(fp)) == EOF) { perror("fclose"); return EOF; } return count; }

執行結果

在這裡插入圖片描述

2、定位流獲取檔案大小fseek(),ftell()

int get_file_size(const char *file)
{
	int count;
	FILE *fp;
	if((fp = fopen(file,"r")) == NULL)//檔案以只讀模式開啟時流的讀寫位置在檔案開頭。若開啟模式是“a”追加,則讀寫位置在檔案末尾
	{
		perror("fopen"
); return -1; } fseek(fp,0,SEEK_END);//將流的讀寫位置定位到檔案末尾 count = ftell(fp);//讀取流的當前讀寫位置 if((fclose(fp)) == EOF) { perror("fclose"); return EOF; } return count; }

執行結果

在這裡插入圖片描述