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.
if anyone know how solve this problem, please answer-me