<stdio.h>
头文件中。size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
#include <stdio.h> struct Student { int id; char name[50]; float grade; }; int main() { FILE *file; file = fopen("students.bin", "wb"); if (file == NULL) { printf("Error opening file!\n"); return 1; } struct Student student1; student1.id = 1; strncpy(student1.name, "Alice", sizeof(student1.name) - 1); student1.grade = 90.5; size_t result = fwrite(&student1, sizeof(struct Student), 1, file); if (result != 1) { printf("Error writing to file!\n"); return 2; } fclose(file); printf("Data written successfully!\n"); return 0; }这段代码创建了一个名为 students.bin 的文件,并在其中写入了一个 Student 结构。如果文件无法打开或写入数据时出现错误,程序会打印错误消息并返回非零退出代码。
本文链接:http://task.lmcjl.com/news/13765.html