1
The file has only 3 lines as content, which must be so:
Idade = 15
Nome = Alvaro
Apelido = Costa
this file is only open for reading with fopen
in "r mode".
So I have 3 variables declared in the code:
int idade;
char nome[10];
char apelido[10];
and I need to retrieve that information from the file and assign to each of the variables its contents-
I read on the internet that function fgets()
could read line by line and place line information for a vector
but what I can do is just read the first line of the file that relates to age
from there it no longer gives.
With the fscanf()
I have to put everything into a vector first and then separate the information from that vector
but I cannot with this function obtain all the contents of the file.
What’s the simplest way to do this?
My idea was to put each line for a separate vector
and ai searched with some function in the first vector digits and converted the string that contained digits to integer and assigned to the variable (int idade
).
In relation to vector 2 that would correspond to the name I ignored the first positions that referred to "Name = " and took advantage of the string of this forward position forming a new vector with only the name. In relation to vector 3 I would do the same treatment as in vector 2, but the problem is that neither putting the total file information inside an array with you.
The ideal I think would be to put each line of the file for an array and from there I already got away.
I also share my code here:
int idade;
char nome[10];
char apelido[10];
void configuracoes(){
// colocando aqui toda a informação do ficheiro
char conteudo[100];
// OU
// será possivel pegar em cada linha de um ficheiro e colocar os seus caracteres directamente para cada um destes vetores?
char linha1[10];
char linha2[10];
char linha3[10];
FILE *f = fopen("dados.txt","r");
// colocar o conteudo do ficheiro para dentro de um vetor
// testativa de colocar todo o conteudo do ficheiro para dentro de um vetor // FALHADA
int i;
for(i=0; i != EOF; i++){
conteudo[i] = fscanf(f,"%c", conteudo);
}
//fgets(conteudo,100,f);
for(i=0; i<100; i++){
printf("%c", conteudo[i]);
}
printf("\n");
fclose(f);
//printf("CONFIGURACAO APLICADA\n");
}
main(){
configuracoes();
return 0;
}
If you are absolutely sure of the file format and are sure that the format will never change, you can do
if (fscanf(f, "Idade =%d Nome =%.9s Apelido =%.9s", &idade, nome, apelido) != 3) /* erro */;
– pmg