【c】文件操作函数:fprintf,fread,fwrite,fseek,ftell,fopen,fclose,fflush以及获取文件长度示例
Date: 2018.9.20
1、参考
http://www.cplusplus.com/reference/cstdio/fprintf/
http://www.cplusplus.com/reference/cstdio/fwrite/
2、 fprintf
关于fprintf的使用可以参考:https://blog.csdn.net/SoaringLee_fighting/article/details/78816023
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:偏移模式,通常为1:SEEK_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
http://www.cplusplus.com/reference/cstdio/fopen/
作用:读取文件指针
FILE * fopen ( const char * filename, const char * mode );
-- filename: 文件路径
-- mode: 文件打开方式
8、fclose
http://www.cplusplus.com/reference/cstdio/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!