0

I open a file and need to print off the names using an array of struct (because I'm going to change the content after, However despite getting the names, I can't store them in the struct. The func[a].nome and the others are blank. Does someone know a way to fix it? Pls don't mind the portuguese.

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

struct Prop
{long int cartaocidadao;
     char nome[60];
     char morada[60];
};
void lerficheiro(){

int Nac,Reg,Dis,Mun;
long int cartaocidadao;
char nome[60],codigopostal[8],morada[60];
int porta,ch, a=0;
char s[100];
FILE *fp;

struct Prop func[2340]; 

 printf("Escreva o nome do ficheiro a abrir (ou ENTER para abrir \"base.txt\") :");
scanf("%s",s);

fp = fopen(s,"r");

if (fp==NULL){
printf("Impossivel ler ficheiro %s\n", s);
exit(2);}

while((ch=fgetc(fp))!=EOF){
fscanf(fp,"%d.%d.%d.%d %ld ",&Nac,&Reg,&Dis,&Mun, &cartaocidadao);
fgets(nome,60,fp);
fgets(morada,60,fp);
fscanf(fp,"%d %s", &porta, codigopostal);
func[a].cartaocidadao = cartaocidadao;
strcpy(func[a].nome, nome);
strcpy(func[a].morada, morada);
a++;

printf("%ld %s \n",cartaocidadao, func[a].nome);
}

}

int main(){
int select=10;


while (select!=0){
Menu1();
printf("selecione:");
scanf("%d", &select);

switch (select){
    case 1: lerficheiro(); break;
    case 2: break;
    case 3: break;
    case 4: break;
    case 5: break;
    case 6: break;
    case 7: break;
    case 8: break;
    case 9: break;

    }
}
}
  • 2
    Does your editor auto-indent? It can make the code a lot more readable, than struggling to find where each function and code block begins/ends. – Weather Vane Dec 02 '19 at 18:32
  • 2
    I see you are freely mixing `fgetc` with `fscanf` and `fgets` which makes the coding task really hard, because they treat whitespace in different ways. I would stick with `fgets` and then apply `sscanf` on the string it reads. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Dec 02 '19 at 18:35
  • Your code looks good. Are you trying to access func[] from outside of lerficheiro ? Your array of struct func[2340] exists only inside lerficheiro. Sorry, I cannot test your code, the part that creates base.txt is missing and Menu1 is missing. – BobRun Dec 02 '19 at 20:10
  • @BobRun it doesn't matter, doesn't work anyway. I can give it to you the base.txt and Menu1 its just a bunch of prints for the user to select lerficheiro() and others... – Simon123 Dec 03 '19 at 10:41
  • If you edit your code and add missing parts, people will be able to help you. As it is now it is impossible to understand why your struct is blank. If you access from outside the function then you need to pass the array to the function. – BobRun Dec 03 '19 at 22:04

0 Answers0