Copying the contents of a file to vectors in c

Asked

Viewed 493 times

-1

Guys, I’m trying to copy a file that has several products, a line with the name and the following with the code, price and quantity. I tried to pass each line to an array, but it’s not working. When I print, it’s 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++;}
  • C is different from C#, please use the tags correctly.

  • how you are declaring the variables name_prod and cod_prod?

  • char nome_prod[1000][100];

  • char cod_prod[1000][100];

  • You could show an example of input formatting?

1 answer

0

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

  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 the product information into the main memory it will work according to your implementation.

It would be ideal for you to know the exact size of every 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 these values and so read all of them 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 I’ve helped in case you get doubts I can try to solve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.