1. 程式人生 > >【c】檔案操作函式:fprintf,fread,fwrite,fseek,ftell,fopen,fclose,fflush以及獲取檔案長度示例

【c】檔案操作函式:fprintf,fread,fwrite,fseek,ftell,fopen,fclose,fflush以及獲取檔案長度示例

Date: 2018.9.20

1、參考

2、 fprintf

3、fread

作用:從一個檔案流中讀取資料。 Read block of data from stream Reads an array of count elements, each one with a size of size bytes, from the stream and stores them in the block of memory specified by ptr. The position indicator of the stream is advanced by the total amount of bytes read. The total amount of bytes read if successful is (size*count).

size_t fread(void *buffer, size_t size, size_t count, FILE *stream);
	  -- buffer:指向資料塊的指標
	  -- size:每個資料的大小,單位為Byte(例如:sizeof(int)就是4)
	  -- count:要讀取的資料的個數
	  -- stream:檔案指標

4、fwrite

作用:將緩衝區中的資料寫入檔案中。 Write block of data to stream Writes an array of count elements, each one with a size of size bytes, from the block of memory pointed by ptr to the current position in the stream. The position indicator of the stream is advanced by the total number of bytes written. Internally, the function interprets the block pointed by ptr as if it was an array of (size*count) elements of type unsigned char, and writes them sequentially to stream as if fputc was called for each byte.

size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
    -- buffer:指向資料塊的指標
    -- size:每個資料的大小,單位為Byte(例如:sizeof(int)就是4)
    -- count:資料個數
    -- stream:檔案指標

5、fseek

作用:重定位檔案指標位置 Reposition stream position indicator For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.

int fseek(FILE *stream, long offset, int fromwhere)

FILE *stream:檔案流指標
long offset:   偏移量大小
int fromwhere:偏移模式,通常為1SEEK_CUR(檔案當前位置) SEEK_SET(檔案開頭) SEEK_END(檔案結尾)。

6、ftell

作用:獲取當前檔案流指標位置。 Get current position in stream Returns the current value of the position indicator of the stream. For binary streams, this is the number of bytes from the beginning of the file.

long int ftell ( FILE * stream );
FILE *stream:檔案流指標

7、fopen

FILE * fopen ( const char * filename, const char * mode );
-- filename:  檔案路徑
-- mode: 檔案開啟方式

8、fclose

int fclose ( FILE * stream );

9、fflush

作用:重新整理流指標

int fflush ( FILE * stream );

Flush stream If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.

10、示例

利用fseek函式和ftell函式獲取檔案長度大小:

int len;
FILE* fp = fopen("log.txt","rb");
fseek(fp, SEEK_SET, SEEK_END); //將檔案指標重定位到檔案末尾
len = ftell(fp); //從檔案開始到檔案末尾的位元組數

THE END!