標籤:blog io os ar 檔案 資料 div on log
最近工作,有個需求需要將YUV的整個檔案讀入記憶體,然後處理這些YUV資料,一種比較有效方法如下:
#include <stdio.h>#include <stdlib.h> int main (){ FILE * pFile; long lSize; char * buffer; size_t result; /* 若要一個byte不漏地讀入整個檔案,只能採用二進位方式開啟 */ pFile = fopen ("test.txt", "rb" ); if (pFile==NULL) { fputs ("File error",stderr); exit (1); } /* 擷取檔案大小 */ fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); /* 分配記憶體儲存整個檔案 */ buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) { fputs ("Memory error",stderr); exit (2); } /* 將檔案拷貝到buffer中 */ result = fread (buffer,1,lSize,pFile); if (result != lSize) { fputs ("Reading error",stderr); exit (3); } /* 現在整個檔案已經在buffer中,可由標準輸出列印內容 */ printf("%s", buffer); /* 結束示範,關閉檔案並釋放記憶體 */ fclose (pFile); free (buffer); return 0;}
在使用者態可以很方便的測試這個例子,可以寫一個簡單的程式,讀入YUV422格式含有多幀的檔案,然後操作這塊記憶體,擷取單獨的Y分量資料和C分量資料,也可以按幀操作此檔案。
C一次將整個檔案讀入記憶體