在C编程中,可以使用fwrite
函数来向文件中写入数据。这个函数可以写入任何数据类型的数据,包括字符串、数字、数组、结构体等等。下面我们就从多个方面对C fwrite
函数进行详细阐述。
一、fwrite
函数的基本用法
size_t fwrite(const void* ptr, size_t size, size_t count, FILE* stream);
该函数用于向文件中写入数据,可以写入任何类型的数据。其中,ptr
为需要写入的数据的指针;size
为每个数据的字节数;count
为要写入数据的数量;stream
为要写入数据的文件指针。
例如,我们要将一个字符串写入到文件中:
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("file.txt", "w");
if (fp == NULL) {
printf("fail to open file\n");
return 0;
}
char str[] = "hello world";
int len = strlen(str);
fwrite(str, sizeof(char), len, fp);
fclose(fp);
return 0;
}
上述代码创建了一个文件指针,打开一个文件并向其中写入了字符串“hello world”。
二、fwrite
函数的返回值及错误处理
fwrite
函数返回成功写入的数据项数量,如果返回值少于count
,说明发生了错误。
通常情况下,fwrite
函数的返回值与count
相等表示写入成功,如果小于count
,则表示发生了错误。我们可以利用ferror
函数来判断是否发生了错误,该函数返回非0值表示发生了错误。调用clearerr
函数可以清除错误标志,以便下一次读写操作。
下面是一个演示fwrite
函数在写入数据过程中的错误处理的示例:
#include <cstdio>
int main()
{
FILE *fp1, *fp2;
char buf[1024];
int n;
fp1 = fopen("input.txt", "r");
fp2 = fopen("output.txt", "w");
if (fp1 == NULL || fp2 == NULL) {
printf("fail to open file\n");
return -1;
}
while ((n = fread(buf, 1, sizeof(buf), fp1)) > 0) {
if (fwrite(buf, 1, n, fp2) != n) {
printf("write error\n");
}
}
if (ferror(fp1)) {
printf("read error\n");
}
clearerr(fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
上述代码演示了如何在读取数据和写入数据时进行错误处理,同时清除错误标志并关闭文件。
三、fwrite
函数的高级应用
1. 向文件中写入结构体数据
通过fwrite
函数,我们可以将任何类型的数据写入文件。我们也可以将结构体写入到文件中,只需要将结构体指针作为数据源传递给fwrite
函数即可。
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
float score;
};
int main()
{
FILE *fp;
fp = fopen("data.txt", "wb");
if (fp == NULL) {
printf("fail to open file\n");
return -1;
}
Student s = {"Tom", 18, 95.5};
fwrite(&s, sizeof(Student), 1, fp);
fclose(fp);
return 0;
}
上述代码演示了如何将一个学生结构体写入文件中。
2. 向文件中写入多维数组
如果需要向文件中写入多维数组,我们需要将其转换成一维数组,并且写入文件的时候,需要按照行优先或者列优先的顺序来写入数据。
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
fp = fopen("data.txt", "wb");
if (fp == NULL) {
printf("fail to open file\n");
return -1;
}
int a[2][3] = {{1,2,3}, {4,5,6}};
int b[6];
memcpy(b, a, sizeof(a)); // 将二维数组转换成一维数组
fwrite(b, sizeof(int), 6, fp); // 写入一维数组
fclose(fp);
return 0;
}
上述代码演示了如何将一个二维数组写入文件中。
3. 向文件中写入二进制数据
如果需要向文件中写入二进制数据,我们可以打开二进制文件,并且需要使用fwrite
函数来写入数据。
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("data.bin", "wb");
if (fp == NULL) {
printf("fail to open file\n");
return -1;
}
char buf[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f};
fwrite(buf, sizeof(char), sizeof(buf), fp);
fclose(fp);
return 0;
}
上述代码演示了如何向文件中写入二进制数据,也就是十六进制字符串“Hello”。