2016-03-10 96 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

对不起,我刚刚有机会回复,非常感谢你的帮助,它帮助我理解了这是如何工作的,我非常感谢你的帮助 –