How to read a file and insert data in c

Asked

Viewed 82 times

0

Hello I’m new in C and have the following doubt

I have a program that needs to save and read student data

Student example below:

 typedef struct academico{
     char nome[50];
     char cidade[30];
     char estado[20];
     char rga[12];
    }aluno;

i can save everything ok. Obs. save the entire structure of a student, per line.

in reading I use a fgets detro of a while until the end of the file to read all the records, inside the while as below

void lerAluno(){

FILE *ptArq;
char str[60];
ptArq = fopen("DadosAlunos", "r");

if(ptArq == NULL){
    printf("erro");
    return 0;
}
char linha[112];

while((fgets(linha, sizeof(linha),ptArq)) != NULL){

  //aqui eu usode uma função para ler a "string" até o ; e colocar dentro de uma variavel
 // porem após o primeiro ; eu não sei de nenhuma forma de separar os dados restantes da mesma forma sem usar um monte de variaveis e while
// é possivel resolver isso com ponteiros seria o ideal

}

Example of how the data is inside the file:

August;treslagoas;ms;654321

Jose;saopaulo;sp;123456

  • I think it would be better if you record and read your structure as a data block. Record with fwrite and read with fread.

  • Search for the Strtok function of <string. h>

  • What’s the problem ? Don’t read correctly ? Gives error ? Doesn’t open the file ? What happens ? How were the values stored in the file ? Which code saved the data ?

1 answer

0

If you want to put the organized record, try this:

fprintf(ponteiroArquivo, "\n------------------------\n");
fprintf(ponteiroArquivo,"nome: %s\n",aluno.nome);
fprintf(ponteiroArquivo,"Cidade: %s\n",aluno.cidade);
fprintf(ponteiroArquivo,"Estado: %s\n",aluno.estado);
fprintf(ponteiroArquivo,"RGA: %s\n",aluno.rga);

fclose(ponteiroArquivo); //fecha o arquivo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.