[英]How to put records from a random access file into an array in the C programming language?
How do I put the records from the random access file DATA.data into the array allRecs[10]? 如何将来自随机访问文件DATA.data的记录放入数组allRecs [10]?
/*Reading a random access file and put records into an array*/
#include <stdio.h>
/* somestruct structure definition */
struct somestruct{
char namn[20];
int artNr;
}; /*end structure somestructure*/
int main (void) {
int i = 0;
FILE *file; /* DATA.dat file pointer */
/* create data with default information */
struct somestruct rec = {"", 0};
struct somestruct allRecs[10]; /*here we can store all the records from the file*/
/* opens the file; exits it file cannot be opened */
if((file = fopen( "DATA.dat", "rb")) == NULL) {
printf("File couldn't be opened\n");
}
else {
printf("%-16s%-6s\n", "Name", "Number");
/* read all records from file (until eof) */
while ( !feof( file) ) {
fread(&rec, sizeof(struct somestruct), 1, file);
/* display record */
printf("%-16s%-6d\n", rec.namn, rec.artNr);
allRecs[i].namn = /* HOW TO PUT NAME FOR THIS RECORD IN THE STRUCTARRAY allRecs? */
allRecs[i].artNr = /* HOW TO PUT NUMBER FOR THIS RECORD IN THE STRUCTARRAY allRecs? */
i++;
}/* end while*/
fclose(file); /* close the file*/
}/* end else */
return 0;
}/* end main */
Two ways immediately come to mind. 立刻想到两种方法。 First, you can simply assign, like this:
首先,您可以像这样简单地分配:
allRecs[i] = rec;
But, judging by your code, you don't even need that - you can simply read directly in the appropriate element: 但是,从您的代码来看,您甚至不需要它-您可以直接在相应的元素中直接阅读:
fread(&allRecs[i], sizeof(struct somestruct), 1, file);
/* display record */
printf("%-16s%-6d\n", allRecs[i].namn, allRecs[i].artNr);
i++;
By the way - are you sure that the file will never contain more than 10 records? 顺便说一句-您确定文件不会包含超过10条记录吗? Because if it does, you'll get into a lot of trouble this way...
因为如果这样做的话,这种方式会给您带来很多麻烦...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.