IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

fichier csv: séparation des lignes avec le langage C


Sujet :

C

  1. #1
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Février 2010
    Messages
    32
    Détails du profil
    Informations personnelles :
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2010
    Messages : 32
    Points : 19
    Points
    19
    Par défaut fichier csv: séparation des lignes avec le langage C
    bonjour,
    je veux séparer les champs d'une ligne d'un fichier csv, j'ai fait la fonction File_Sep qui sépare chacune des ligne ensuite fait appel à une fontion sep_line qui va séparer les champs de chacune des lignes.
    pour cela j'ai utilisé une pile:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
     
     typedef struct pile {
           char* content;
           struct pile * prev;
          } pile;
     
     void Push(pile **p, char* Val)
        {
                    pile *element=(pile*)calloc(1,sizeof(pile*));
                    if (element == NULL)
                    {
                        printf("can not allocate a new element\n");
                        exit(0);
                    }
     
                    else
                    {
                        element->content = Val; 
                        printf("push done for %s \n", (char*) element->content );
                        element->prev = *p;
                        *p = element;       
                    }
        }
     
     
        /* Function allowing to remove an element from the "pile" */
     
        char* Pop(pile **p)
     
        {    char * Val;
                pile *tmp;
            if(p == NULL) return ("\n");     /* Returns \n if the "pile is empty */
                tmp = (*p)->prev;
            printf("before copiying the pile's content \n");
                Val = strdup((*p)->content);
            strcat(Val,"\0");
                free(*p);
                *p = tmp;       /* The pointer points to the last element */
            printf("the value of the Pop is: %s  \n",Val);
                return Val;     /* Returns the value popped from the "pile" */
        }
     
        /* Function allowing to view the content of the pile */
     
      void View(pile *p)
        {
               printf("in View\n");
                while(p)
                  {
                     printf("%s \n", strdup(p->content));
                     p = p->prev;
                  }
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
     
    static pile** File_Sep (char* filename)
    {
     
    printf("Beginning of File_Sep() \n");
    int NL;
    int NF;
    NL = line_count (temp);
    NF = field_count (temp);
    FILE *file_in; /* stream associated to temp: the copy of the original client's file */
     
    /* We will store each line in a char* variable and then we will separate its fields */
     
    pile** TAB = (pile**)malloc (MAX_NB_LINES * sizeof(pile**));
    /* TAB is an array of "pile" i.e each compartment of TAB will contain a pointor to "pile" which itself will contain fields of the line n— i of the file */
    int c;
    int i =0;
    char* line_in = (char*)malloc(sizeof(char*) * MAX_LINE_LEN);
    long int L=0;  /* The variable L will contain the size already read from the file */
    file_in = fopen (filename, "r");
    fseek (file_in, 0L, SEEK_SET) ;
     
        while ((c != EOF) && (c != '\n'))  /* start while 1 */
        {
          c=getc(file_in) ;
          printf("We will copy the line N° %d \n", i+1);
                i++;
             fgets (line_in, MAX_LINE_LEN, file_in);  /* line_in contains the first line in the first iteration */
     
            L = L + strlen(line_in);
            fseek (file_in, L, SEEK_SET); /* To be sure that we are in the line just following the line already read */
            TAB[i] = (pile*)malloc(sizeof(pile*));
            TAB[i] = NULL;
            TAB[i]= Sep_Line(line_in);
            View(TAB[i])  ;
       } /* fin de while 1 */
     
     
    fclose(file_in);
    printf("End of File_Sep() \n \n");
     
    return (TAB);
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
     
    /*begining of  main() */
        int main(int argc, char *argv[])
     
        {
     
          int m=3;
          int n=2;
     
          pile* conf = (pile*)malloc(sizeof(pile*));
          conf=NULL;
     
          pile** TAB = (pile**)malloc (MAX_NB_LINES * sizeof(pile**));
          TAB =  File_Sep(argv[1]);
          int i =0;
          printf("the view of the values \n");
          for(i=0; i<n; i++)
          {
            View(TAB[i]) ;
          }
          char* REQ=(char*)malloc(100*sizeof(char*));
     
          char** Field = (char**)malloc(MAX_NB_LINES * sizeof(char**) * MAX_FIELD_NAME_LEN);
          char* field_name =(char*)malloc(MAX_FIELD_NAME_LEN *sizeof(char*));
     
          Push(&conf,"prenom");
          Push(&conf,"nom");
          Push(&conf,"ville");
     
          printf("\n");
          printf("before the view of the pile conf \n");
          View(conf);
          printf("After the pile view \n");
     
          char tab_name[5]="BADR";
     
         int  field_counter,line_counter;
        field_counter=0;
            do
             { 
              printf(" We are popping the field number %i from the file  \n ", m-field_counter);
               printf("Before the Pop() \n");
               field_name = Pop(&conf);
    &nbsp;&nbsp;&nbsp;&nbsp;   printf("the col's name is :%s \n",  field_name);
     
              for (line_counter=0; line_counter<n; line_counter++) /* start for 2 */
              {
     
    &nbsp;&nbsp;&nbsp;&nbsp;    printf("allocattion \n");
    &nbsp;&nbsp;&nbsp;&nbsp;    Field[line_counter]= (char*)malloc(MAX_FIELD_NAME_LEN * sizeof(char*));
    &nbsp;&nbsp;&nbsp;&nbsp;    printf("pop of the value \n");
                Field[line_counter]= Pop(&TAB[line_counter]);
     
              /* The array Field will contain in every compartment a value of the sama column */
               REQ = create_query(tab_name, field_name, Field[line_counter]);
               printf("la requete est: \n %s \n ",REQ);
                     //   EXEC SQL EXECUTE IMMEDIATE :REQ;
                     printf("on va executer la requête \n");    
     
              } /* END for 2 */
    &nbsp;&nbsp;&nbsp;&nbsp;  field_counter++;
    &nbsp;&nbsp;&nbsp;&nbsp;  printf("field_counter %d \n",field_counter);
        }
     
          while (conf != NULL); /* The "pile" containing the field's names is empty so we stop because 
                                         this means that the array containing cleint's data reached its end */
     
        }
    lors de l'exécution j'ai eu cette trace:
    Beginning of File_Sep()
    We will copy the line N° 1
    Beginning of Sep_Line() for the line: meriem,zorai,bizerte

    the field's now is : meriem
    push done for meriem
    the rest from the line is :zorai,bizerte
    ,
    the field's now is : zorai
    push done for zorai
    the rest from the line is :bizerte
    ,
    the field's now is : bizerte

    push done for bizerte

    the rest from the line is :
    End of Sep_Line() for the line: meriem,zorai,bizerte

    in View



    We will copy the line N° 2
    Beginning of Sep_Line() for the line: maha,gmati,tunis

    the field's now is : maha
    push done for maha
    the rest from the line is :gmati,tunis
    ,
    the field's now is : gmati
    push done for gmati
    the rest from the line is :tunis
    ,
    the field's now is : tunis

    push done for tunis

    the rest from the line is :
    End of Sep_Line() for the line: maha,gmati,tunis

    in View



    End of File_Sep()

    the view of the values
    in View
    in View
    ÿ¿
    ÿ¿
    ÿ¿
    push done for prenom
    push done for nom
    push done for ville

    before the view of the pile conf
    in View
    ville
    nom
    prenom
    After the pile view
    We are popping the field number 3 from the file
    Before the Pop()
    before copiying the pile's content
    the value of the Pop is: ville
    the col's name is :ville
    allocattion
    pop of the value
    Segmentation Fault
    donc il ne me visualise pas le contenu des piles contenant les champs des lignes!!!!!!

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Novembre 2008
    Messages
    15
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2008
    Messages : 15
    Points : 17
    Points
    17
    Par défaut
    Bonjour,

    tout d'abord ceci peut aider.
    http://en.wikipedia.org/wiki/CSV_application_support

    ensuite... j'avoue que de mon cote l'affichage du code beug... et que c'est assez indigeste a lire sur une ligne...

    Par rapport a la structure du CSV, tu peux directement retraiter.
    -> separer les termes au niveau du separateur choisi (','), et au bout de x occurences (le nombre present sur la premiere ligne, tu considere que la suite est sur la ligne suivante,
    si tu ne vois pas de saut de ligne ( precede ou non de caracteres neutres [par exemple espace ou tab ou aucun... suivant tes preferences]), alors tu sais rapidement qu'il y a une erreur.

    (si je vois le code sur plusieurs ligne, je regarderais peut etre plus en avant).
    mais je peux deja te dire que les messages d'erreur s'affiche sur la sortie d'erreur de preference. (fprintf(stderr, "%s\n", str); par exemple).



    ----

    il y'a trop d'allocation de memoire, et de strdup inutile, et du coup pas assez de free.
    la methode pour lire le fichier ne m'enchante pas... ( j'avoue pas bien comprendre l'utilisation de la taille de la plus grande ligne... partout...)
    Je te conseille de lire tout le fichier d'un coup, et de le parser ensuite.
    Tant que tu n'as pas de "\n" alors tu es sur la meme ligne.

  3. #3
    Expert éminent sénior
    Avatar de diogene
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Juin 2005
    Messages
    5 761
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2005
    Messages : 5 761
    Points : 13 926
    Points
    13 926
    Par défaut
    Première constatation, tous les malloc()/calloc() sont faux, à commencer par celui-ci qui alloue de la mémoire pour un pointeur et pas pour une struct pile :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     void Push(pile **p, char* Val)
        {
                    pile *element=(pile*)calloc(1,sizeof(pile*)); ....
    qui devrait être
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    pile *element = calloc(1,sizeof(pile)); 
    // ou 
    pile *element = calloc(1,sizeof *element);
    Même erreur pour tous les autres.
    Publication : Concepts en C

    Mon avatar : Glenn Gould

    --------------------------------------------------------------------------
    Une réponse vous a été utile ? Remerciez son auteur en cliquant le pouce vert !

Discussions similaires

  1. Réponses: 4
    Dernier message: 26/06/2012, 11h34
  2. Importer des fichiers CSV dans SQL Server avec SSIS
    Par nathantahiti dans le forum SSIS
    Réponses: 4
    Dernier message: 02/08/2011, 16h09
  3. Réponses: 3
    Dernier message: 11/06/2007, 11h20
  4. Réponses: 4
    Dernier message: 01/03/2006, 11h35
  5. [Requete] Comment ignorer des lignes avec un LOAD DATA
    Par frangin2003 dans le forum Langage SQL
    Réponses: 2
    Dernier message: 09/11/2005, 12h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo