1 函数原型
fwrite():将数据块写入指定流stream,函数原型如下:
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
cstdio库描述如下:
Write block of data to stream
1. 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.
2. The position indicator of the stream is advanced by the total number of bytes written.
3. 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.
2 参数
fwrite()函数有四个参数ptr、size、count和stream:
- 参数ptr是指向某内存区域的指针,类型为void*型;ptr指向的内存区域存储着待写入文件的数据块;
- 参数size是fwrite()函数要写入的数据项的大小,类型为size_t型,单位为字节;
- 参数count是fwrite()函数要写入的数据项的个数,类型为size_t型;
- 参数stream是fwrite()函数要写入的流,类型为FILE*;stream主要是文件流,就是fopen()函数的返回值。
cstdio库描述如下:
ptr
1. Pointer to the array of elements to be written, converted to a const void*.
size
1. Size in bytes of each element to be written.
2. size_t is an unsigned integral type.
count
1. Number of elements, each one with a size of size bytes.
2. size_t is an unsigned integral type.
stream
1. Pointer to a FILE object that specifies an output stream.
3 返回值
fwrite()函数的返回值类型为size_t型,返回成功写入文件的数据项的数量:
- 返回值等于count,说明数据全部成功写入;
- 返回值小于count,说明数据部分成功写入,写入过程中遇到错误。
cstdio库描述如下:
1. The total number of elements successfully written is returned.
2. If this number differs from the count parameter, a writing error prevented the function from completing. In this case, the error indicator (ferror) will be set for the stream.
3. If either size or count is zero, the function returns zero and the error indicator remains unchanged.
4. size_t is an unsigned integral type.
4 示例
4.1 示例1
使用fwrite()函数将整形数据写入二进制文件,示例代码如下所示:
int main()
{
//
FILE* fp = NULL;
int count = 0;
int wdata = 0;
//
fp = fopen("1.dat", "wb");
if (fp == NULL) {
perror("Failed to open file ");
exit(1);
}
//
for (count = 0; count < 10; count++) {
wdata = count + 0x60;
fwrite(&wdata, sizeof(int), 1, fp);
}
//
fclose(fp);
//
return 0;
}
代码运行结果如下图所示:
4.2 示例2
使用fread()函数和fwrite()函数实现文本文件拷贝功能,示例代码如下所示:
int main()
{
//
FILE* fpr = NULL;
FILE* fpw = NULL;
char rwBuf[80] = { 0 };
int rdItem = 0;
//
fpr = fopen("1.txt", "rb");
fpw = fopen("2.txt", "wb");
//
if (fpr == NULL || fpw == NULL)
{
perror("Failed to open file ");
exit(1);
}
//
while ((rdItem = fread(rwBuf, 1, 80, fpr)) > 0)
{
fwrite(rwBuf, 1, rdItem, fpw);
}
//
fclose(fpr);
fclose(fpw);
//
return 0;
}
文件内容如下图所示:
代码运行结果如下图所示:
代码及运行结果分析如下:
- 注意:fread()函数读多少字符,fwrite()函数写多少字符;
- 文件1.txt和2.txt的内容和大小完全一致,说明文件拷贝功能正常。