Thread: Structure Dynamic with File Write

  1. #1
    Registered User
    Join Date
    Mar 2005

    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:
    #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;
    /* fim do modelo */
    int main(int argc,char **argv){
      FILE *fp;
      register int i;
      short int n_estruct;
      char op;
      modelo *p_estruct;
        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]);
        printf("Erro ao abrir o arquivo %s.\n",argv[1]);
      puts("****************Inicio da List..........**************");
      fputs("Quantas listas deseja entrar: ",stdout);
      if(!(p_estruct=(modelo *)malloc(n_estruct*sizeof(modelo)))){
        printf("Erro ao Alocar %s estruturas.\n",n_estruct);
      else printf("Alocado com Sucesso.\n");
        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);
      printf("\nDeseja gravar no arquivo %s?[S/N]",argv[1]);
          if(fwrite((modelo *)&p_estruct,sizeof(modelo),1,fp)!=1){
    	printf("Erro na gravacao.\n");
      //fputs("Gravado com sucesso!\n",stdout);
      return 0;
    And now go to error message when I type S to confirm the write in my program.
    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
    The edge of the known universe
    Step 1 is pay attention to your compiler error messages
    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
    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