2016-03-10 97 views
0

你好這是我學習c編程的第一年,我花了整整一天的時間試圖找出這一個,現在我頭痛 無論如何,我只是想保持這個儘可能簡單,這裏是一個測試代碼,我想糾正,所以我可以理解這是如何工作的 我想要做的是在文本文件中存儲結構變量的動態數組,然後從該文本文件中讀取數據一個動態數組。 這是c語言以c語言在文本文件中存儲結構的動態數組

#include <stdio.h> 
#include <stdlib.h> 
struct student { 
char nam[3];  // we store to this 
char testname[3]; // we read to this 
}*science[10]; 
int main() { 
int i; 
FILE *ptr=fopen("science_class","a"); 
for (i=0;i<3;i++){   //storing the infro from dynamic array into the file 
e[i]=(science*)calloc(3,sizeof(char)); 
puts("enter name"); 
gets(science[i]->name); 
fprintf(ptr,"%s",science[i]->name); } 
for (i=0;i<3;i++){   // loading the info from the file to a dynamic array 
fscanf(ptr,"%s",&science[i]->testname) 
printf("name :%s \n",science[i]->testname) } 
fclose(ptr); 

} 

回答

1

我寫了,有一個car結構簡單的C程序。該程序只是將有關汽車的數據讀入動態數組並將其寫回到另一個文件。希望你理解的概念:

#include<stdio.h> 
#include<stdlib.h> 

struct car 
{ 
    char name[20]; 
    char color[20]; 
    float mass; 
    int price; 
}; 
typedef struct car Cars; 

int main() 
{ 
    int i, n; 
    Cars *cars; 
    ///////// READ: 
    FILE *in = fopen("cars_in.txt", "r"); 
    fscanf(in, "%i", &n); //read how many cars are in the file 
    cars = (Cars*)malloc(n*sizeof(Cars)); //allocate memory 

    for (i = 0; i < n; ++i) //read data 
    { 
     fscanf(in, "%s", cars[i].name); 
     fscanf(in, "%s", cars[i].color); 
     fscanf(in, "%f", &cars[i].mass); 
     fscanf(in, "%i", &cars[i].price); 
    } 

    fclose(in); 


    ///////////// WRITE: 
    FILE *out = fopen("cars_out.txt", "w"); 
    fprintf(out, "%d\n", n); 
    for (i = 0; i < n; ++i) 
    { 
     fprintf(out, "%s ", cars[i].name); 
     fprintf(out, "%s ", cars[i].color); 
     fprintf(out, "%f ", cars[i].mass); 
     fprintf(out, "%i\n", cars[i].price); 
    } 

    fclose(out); 
    free(cars); 
    return 0; 
} 

,這裏是一些數據,你應該把在cars_in.txt

5 
BMW red 1500 80000 
Opel black 950 15000 
Mercedes white 2500 100000 
Ferrari red 1700 2000000 
Dodge blue 1800 750000 

編輯: 我只是改變fscanfscanf和工作正常。輸入數據時要小心:首先你要告訴你要添加多少cars以便malloc可以在輸入汽車的名稱 - >顏色 - >質量 - >價格後用白色字符(輸入,空格,標籤)。 只要改變讀出部分,代碼的其餘部分保持不變:

///////// READ FROM KEYBOARD 

scanf("%d", &n); // first we have to know the number of cars 

cars = (Cars*)malloc(n*sizeof(Cars)); //allocate memory 

for (i = 0; i < n; ++i) //read data -> be careful: you have to keep the order 
{ 
    scanf("%s", cars[i].name); 
    scanf("%s", cars[i].color); 
    scanf("%f", &cars[i].mass); 
    scanf("%i", &cars[i].price); 
} 
+0

這是什麼人做的,它需要的第一個文件的內容,並把它複製到第二個文件, 我更換第一個fscanf行與此 scanf(「%s」,cars [i] .name); scanf(「%s」,cars [i] .color); scanf(「%f」,&cars [i] .mass); 012fscanf(「%i」,&cars [i] .price); 所以我可以手動輸入數據,但程序後,我已完成鍵入他們的手指,我仍然不能存儲在文本文件中的數據可以ü請幫助我, –

+0

對不起,我回答這麼晚,希望你明白,我不知道我的英語說得很好 –

+0

對不起,我剛剛有機會回覆,非常感謝你的幫助,它幫助我理解了這是如何工作的,我非常感謝你的幫助 –