Copying the contents of a file to vectors in c

0

Folks, I'm trying to copy a file that has multiple products, one line with the name and the following with the code, price, and quantity. I tried to pass each line to a vector, but it is not working. When I print, it is not correct.

 fp = fopen("Produtos.txt","r");

if ((fp = fopen("Produtos.txt","r")) == NULL ){
     printf("Erro na abertura do arquivo!!!!");
     return (0);
}
while (1){
    if(feof(fp)) break;

    fgets(nome_prod[i],100,fp);
    fgets(cod_prod[i],100,fp);
    fscanf(fp,"%f",&preco_prod[i]);
    fscanf(fp,"%d",&quant_prod[i]);
    i++;}
    
asked by anonymous 23.06.2017 / 14:51

1 answer

0

I would change the functions you are using to capture the data in the file.

  char nome_prod[100];
  char cod_prod[100];
  int quant_prod;
  float preco_prod;

  while (1){

     if(feof(fp)) break;

     fread(&nome_prod,1,100,fp);
     fread(&cod_prod,1,100,fp);
     fread(&quant_prod,1,4,fp);
     fread(&preco_prod,1,4,fp);
  }

I'm not sure if it's your goal, but if your goal is to bring product information into main memory this will work according to your implementation.

It would be ideal to know the exact size of any 1 Product structure since you used fixed size to store the data in the file. So if you had for example char name [100]; char cod [100]; int quant; float price; you could do the calculation of 100 + 100 + 4 + 4 = 208 and create a struct with those values and so read them all at once like this:

 struct Produtos{

       char nome[100];
       char cod[100];
       int quant;
       float preco;   
};


 struct Produtos prod;  
 fread(&prod,1,208,fp);

I hope to have helped if in doubt I can try to solve.

    
24.06.2017 / 20:28