fwrite函数的用法
时间: 2023-09-08 11:09:58 浏览: 36
fwrite函数是C语言中用于将数据写入文件的函数,其函数原型为:
```C
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
```
函数参数说明:
- ptr:要写入数据的指针
- size:要写入数据块的大小,单位为字节
- count:要写入的数据块的数量
- stream:文件指针,指向要写入数据的文件
函数返回值为实际写入的数据块数量。
示例代码:
```C
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
FILE *fp = fopen("test.txt", "w");
if(fp == NULL) {
printf("Failed to open file.\n");
return -1;
}
int len = strlen(str);
int n = fwrite(str, sizeof(char), len, fp);
printf("Successfully wrote %d bytes to file.\n", n);
fclose(fp);
return 0;
}
```
以上代码将字符串"Hello, world!"写入文件test.txt中,输出结果为"Successfully wrote 13 bytes to file.",表示成功写入了13个字节的数据。