将结构数组放入文件并读取它
Posted
技术标签:
【中文标题】将结构数组放入文件并读取它【英文标题】:Putting struct array into file and reading it 【发布时间】:2021-03-15 23:01:22 【问题描述】:我想将一个结构数组放入一个文件中,并将一个整数放入同一个文件中(我想对数组使用 fwrite())。当我尝试阅读它时,似乎出现了问题。我是 C 的新手,所以也许你可以向我解释它是如何工作的。提前致谢。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Data
char street[40];
char building[10];
char email[30];
unsigned long long number;
Data;
int main()
Data data[3];
Data output[3];
int size = 2;
int sizeout;
// putting something inside
strcpy(data[0].building, "11");
strcpy(data[0].email, "a@a.a");
data[0].number = 37068678102;
strcpy(data[0].street, "Street1");
strcpy(data[1].building, "21");
strcpy(data[1].email, "b@b.b");
data[1].number = 37068678432;
strcpy(data[1].street, "Street2");
//writing into file (I want to use "wb")
FILE *write;
write = fopen("temp.bin","wb");
//if I understand correctly, fprintf is the way to put in an integer
fprintf(write,"%d",size);
//putting array in
fwrite(data,sizeof(Data),2,write);
fclose(write);
FILE *read;
fseek(read, 0, SEEK_SET);
read = fopen("temp.bin","rb");
//gettinf the int out
fscanf(read,"%d",&sizeout);
//getting array out
fread(output,sizeof(Data),2,read);
fclose(read);
//printing what I got
for(int i = 0; i < sizeout; ++i)
printf("First struct: %s %s %s %llu\n", output[i].building, output[i].email, output[i].street, output[i].number);
return 0;
【问题讨论】:
你在read
指针上调用fseek
fopen
之前。
@user3121023 如果我使用 fwrite 整数它会崩溃,至于 data[0] 这是一个疏忽,无论如何谢谢:)
【参考方案1】:
这是您的代码,但更简洁。这家伙说的是真的
你在fopen
之前的读指针上调用fseek
。
但这也不是必需的,因为当您在r
中打开文件时,指针将始终位于第一个位置
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#define doc "doc.bin"
typedef struct Data
char street[40];
char building[10];
char email[30];
unsigned long long number;
Data;
int sizeofdata = sizeof(Data);
int main()
FILE *f;
f = fopen(doc, "wb"); //if you want to open it in w remember that all that is contained with in will be erased , i recomend a+b
Data data[3];
Data output[3];
int size = 2;
int sizeout;
// putting something inside
strcpy(data[0].building, "11");
strcpy(data[0].email, "a@a.a");
data[0].number = 37068678102;
strcpy(data[0].street, "Street1");
fwrite(&data, sizeofdata,1, f);//the one represents the quantitie of regiesteres you wanna imput , you can make it a variable
fclose(f);
if ((f=fopen(doc,"rb"))!=NULL)//this makes for a cleaner solution it will be simpeler in the long run
while (!feof(f))
fread(&output, sizeofdata,1, f);
if (!feof(f))
printf("First struct: %s %s %s %llu\n", output[0].building, output[0].email, output[0].street, output[0].number);
【讨论】:
以上是关于将结构数组放入文件并读取它的主要内容,如果未能解决你的问题,请参考以下文章
逐行读取Javascript中的.csv文件,并使用while循环将其放入数组中