2009-11-12 2 views
0

랜덤 액세스 파일 DATA.data의 레코드를 배열 allRecs [10]에 넣으려면 어떻게해야합니까?랜덤 액세스 파일의 레코드를 C 프로그래밍 언어의 배열에 저장하는 방법은 무엇입니까?

/*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 */ 
+0

숙제? 그렇다면 태그를 붙이십시오. – shank

답변

1

두 가지 방법이 즉시 적용됩니다. 첫째, 당신은 단순히 다음과 같이 지정할 수 있습니다 : 당신의 코드에 의해 판단,

allRecs[i] = rec; 

을, 당신은 심지어 필요하지 않습니다 - 당신은 단순히 해당 요소에 직접 읽을 수 있습니다

fread(&allRecs[i], sizeof(struct somestruct), 1, file); 
/* display record */ 
printf("%-16s%-6d\n", allRecs[i].namn, allRecs[i].artNr); 
i++; 

으로 방법 - 파일에 10 개가 넘는 레코드가 포함되지 않도록 하시겠습니까? 왜냐하면 그렇게한다면, 당신은 이런 식으로 많은 어려움을 겪을 것입니다 ...

+0

아니요. 어떻게 동적으로 만들 수 있는지 잘 모르겠습니다. –

관련 문제