2009-11-12 36 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 2009-11-12 13:53:38

回答

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

不,我不確定你如何讓它變得動態? – 2009-11-12 14:17:39

相關問題