使用C将结构读/写到文件
fwrite(),fread()用于写入C语言中的文件。
fwrite()语法
fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
哪里
ptr-指向要写入的元素数组的指针
size-要写入的每个元素的大小(以字节为单位)
nmemb-元素数量,每个元素的大小为字节
stream–指向指定输出流的FILE对象的指针
fread()语法
fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
哪里
ptr-指向最小大小为size*nmemb字节的内存块的指针。
size-要读取的每个元素的大小(以字节为单位)。
nmemb-元素数,每个元素的大小为字节。
stream-指向指定输入流的FILE对象的指针。
算法
Begin
Create a structure Student to declare variables.
Open file to write.
Check if any error occurs in file opening.
Initialize the variables with data.
If file open successfully, write struct using write method.
Close the file for writing.
Open the file to read.
Check if any error occurs in file opening.
If file open successfully, read the file using read method.
Close the file for reading.
Check if any error occurs.
Print the data.
End.这是在C中读取/写入结构的示例:
范例程式码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int roll_no;
char name[20];
};
int main () {
FILE *of;
of= fopen ("c1.txt", "w");
if (of == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit (1);
}
struct Student inp1 = {1, "Ram"};
struct Student inp2 = {2, "Shyam"};
fwrite (&inp1, sizeof(struct Student), 1, of);
fwrite (&inp2, sizeof(struct Student), 1, of);
if(fwrite != 0)
printf("Contents to file written successfully !\n");
else
printf("Error writing file !\n");
fclose (of);
FILE *inf;
struct Student inp;
inf = fopen ("c1.txt", "r");
if (inf == NULL) {
fprintf(stderr, "\nError to open the file\n");
exit (1);
}
while(fread(&inp, sizeof(struct Student), 1, inf))
printf ("roll_no = %d name = %s\n", inp.roll_no, inp.name);
fclose (inf);
}乌普特
Contents to file written successfully ! roll_no = 1 name = Ram roll_no = 2 name = Shyam
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短