Read comma-separated file data in C

Asked

Viewed 4,172 times

2

I need to read the data of an entry in the format:

100,Refrigerator,180,90,89,1200.00,4,white

After some researches, I found the Strtok function that separates the data between commas, and the code was as follows:

#include <string.h>
#include <stdio.h>

int main(){
    const char s[2] = ",";
    char *token;
    char linha[90];
    char *result;

    FILE *arq;
    if((arq = fopen("eletro.txt", "r")) == NULL){
        printf("Erro ao abrir o arquivo.\n");
    }

   token = strtok(arq, s);

   while (!feof(arq)){
      result = fgets(linha, 90, arq);

      if (result) 
      token = strtok(result, s);


   while( token != NULL ){
        printf( " %s\n", token );
        token = strtok(NULL, s);
   }

  }
  fclose(arq);

    return(0);
}   

The output of this file is exactly the way I wanted it, but my question is: how to save this data in the output format in their respective vectors, divided in the form eletro[i]. codigo, eletro[i]. name (...) until the end, and I need to read several lines of data? Or, there is a simpler way to do this?

  • 2

    You have to create a structure with the data you want and then use that structure in a list. Note that you must always allocate each structure (per line) you read and guards.

  • The structure is created, in this case. I just don’t understand in what way I will read, in what part of the code!

  • Look at my answer.

2 answers

3

Here’s a little explanation in the code of how to do.

#include <string.h>
#include <stdio.h>

struct Eletro
{
    //os teus campos
};

struct Eletro eletro[100];

int main()
{
   const char s[2] = ",";
   char *token;
   char linha[90];
   char *result;

   FILE *arq;
   if((arq = fopen("eletro.txt", "r")) == NULL)
   {
       printf("Erro ao abrir o arquivo.\n");
   }
   token = strtok(arq, s);

   // se precisares do "i" para inserir em array basta inicializares aqui
   int i = 0;
   while (!feof(arq) && i<100) //para garantir que não passa do tamanho da lista.
   {
      result = fgets(linha, 90, arq);

      if (result) 
          token = strtok(result, s);

      //Alocas aqui a estrutura de dados para um elemento.
      int j = 0;
      while( token != NULL )
      {
        //Fazes aqui a tua inserção campo a campo no teu elemento. 
        // exemplo: 
        switch(j)
        {
            case 0:
                eletro[i].codigo = token;
                break; 
            case 1:
                eletro[i].nome = token;
                break; 
            //e continuas consoante os campos que tiveres
        }

        //Outro exemplo:
        // if( j==0 )
        //     eletro[i].codigo = token;
        //...

        printf( " %s\n", token );
        token = strtok(NULL, s);
        j++;
      }
      //passas aqui para o próximo elemento da tua lista.
      i++;
  }
  fclose(arq);

  return(0);
}

Ideone example

  • Jorge did not understand his code very well, what it does token = Strtok(Arq, s); ?

  • @YODA as you can see in the ideone example Strtok separates a string by a certain delimiter, i.e., strtok("teste:ideone", ":") would give the result of a pointer(pointer) with its first element "test" and the second "ideone".

0

a cool example of how to save structures to read files...

    struct suaEstrutura
    {
      char exemplo[50];

    };


    int main()

    {

    FILE *arquivo;
    struct suaEstrutura p;

    arquivo = fopen("seuDiretorio.txt", "a");

    printf("\ninforme seu exemplo: ");
    gets(p.exemplo);

    //Realizando escrita do tamanho de uma estrutura...
    fwrite(&p, sizeof(p), 1, arquivo);

    //explicando o que ta rolando no fwrite: 
    //ele atribui no arquivo, o endereço de p "com os dados", com o tamanho de p, e o contador.
    fclose(arquivo);



    }

Browser other questions tagged

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