Thread: Structure Dynamic with File Write

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    18

    Structure Dynamic with File Write

    my problem is in this code that do for the morning for allocate structures conform the user want. After allocated, he write to the file entred as second argument in the call of program in mode text(I use the linux).
    Here this code and bellow goes the error message:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<ctype.h>
    #define TAM 80
    /******************************************
     * definicao do modelo de estrutura que sera usado pelo programa
     *  para gerar uma lista de dados em um arquivo 
     ******************************************/
    typedef struct{
      char nome[TAM];
      char end[40];
      char bairro[25];
      short int idade;
    }modelo;
    /* fim do modelo */
    int main(int argc,char **argv){
      FILE *fp;
      register int i;
      short int n_estruct;
      char op;
      modelo *p_estruct;
      if(argc!=2){
        printf("Modo de Usar: %s nome_arquivo\nOnde nome_arquivo eh o nome do arquivo onde se deseja criar para gravar os dados.\n",argv[0]);
        exit(1);
      }
      if(!(fp=fopen(argv[1],"w+"))){
        printf("Erro ao abrir o arquivo %s.\n",argv[1]);
        exit(1);
      }
      puts("****************Inicio da List..........**************");
      fputs("Quantas listas deseja entrar: ",stdout);
      scanf("%d",&n_estruct);
      if(!(p_estruct=(modelo *)malloc(n_estruct*sizeof(modelo)))){
        printf("Erro ao Alocar %s estruturas.\n",n_estruct);
        exit(1);
      }
      else printf("Alocado com Sucesso.\n");
      for(i=0;i<n_estruct;i++){
        getchar();
        fputs("Nome: ",stdout);fgets(p_estruct[i].nome,TAM*sizeof(char),stdin);
        fputs("Endereco: ",stdout);fgets(p_estruct[i].end,40*sizeof(char),stdin);
        fputs("Bairro: ",stdout);fgets(p_estruct[i].bairro,25*sizeof(char),stdin);
        fputs("Idade: ",stdout);scanf("%d",&p_estruct[i].idade);
      }
      getchar();
      printf("\nDeseja gravar no arquivo %s?[S/N]",argv[1]);
      op=getc(stdin);
      if(toupper(op)=='S'){
        for(i=0;i<n_estruct;i++){
          if(fwrite((modelo *)&p_estruct,sizeof(modelo),1,fp)!=1){
    	printf("Erro na gravacao.\n");
    	exit(1);
          }
        }
      }
      fclose(fp);
      //fputs("Gravado com sucesso!\n",stdout);
      puts("*****************FIM******************");
      return 0;
    }
    And now go to error message when I type S to confirm the write in my program.
    Code:
    Segmantation fault
    if anyone know how solve this problem, please answer-me
    /**************Um abraço*************/

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Step 1 is pay attention to your compiler error messages
    Code:
    gcc -Wall -W -ansi -pedantic hello.c
    hello.c: In function `main':
    hello.c:32: warning: int format, different type arg (arg 2)
    hello.c:34: warning: format argument is not a pointer (arg 2)
    hello.c:43: warning: int format, different type arg (arg 2)
    hello.c:57: parse error before '/' token
    Step 2 is remove all those redundant casts - this is C remember.
    >if(!(p_estruct=(modelo *)malloc(n_estruct*sizeof(modelo))))
    >if(fwrite((modelo *)&p_estruct,sizeof(modelo),1,fp)!=1)

    Step 3, consistency
    > register int i;
    > short int n_estruct;
    There's no need for declaring things as register, and why not make them both the same type?

    > getchar();
    > op=getc(stdin);
    Two different ways of reading input here - be consistent.

    > puts("****************Inicio da List..........**************");
    > fputs("Quantas listas deseja entrar: ",stdout);
    Two different ways of creating output here - be consistent.

    Step 4 - formatting
    A blank line or two would really help break up the separate areas of your code

    Now the major problem
    > if(fwrite((modelo *)&p_estruct,sizeof(modelo),1,fp)!=1)
    You don't use your loop variable to step through your allocated array
    Code:
    if ( fwrite ( &p_estruct[i], sizeof(modelo), 1, fp ) != 1 )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM