Reading file in C

Asked

Viewed 298 times

4

I use the following structure to read each line of a file:

fclose(arq); // fecha o arquivo para em seguida abri-lo em modo leitura apenas
arq = fopen(url, "r");
if(arq == NULL) {
    printf("Erro, nao foi possivel abrir o arquivo\n");
} else {
    system("cls");
    printf("\n **************************************** NOME DA EMPRESA - LISTA DE CLIENTES ****************************************\n\n");
    fflush(stdin);
    while (fgets(linha, TAM_BUFFER, arq)) { // lê cada linha do arquivo por vez, cada linha está na variável buffer
        printf("Cliente %d:\n", idx);
        idx++;
        fflush(stdin);
        // para cada linha capturada, atribui um valor a variável, para em seguida fazer a impressão
        fscanf(arq, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo);

Problems:

  1. the first line is not printed (I believe the program is reading a ENTER and goes to the second line, I just don’t see where);
  2. after printing the first line (which is actually the second), the Third Client’s CPF is printed separately;
  3. the data of the third customer are not printed, hence jumps to the fourth customer, as well as second customer, the data are printed correctly.

This sequence of problems is the pattern of the answer.

inserir a descrição da imagem aqui

Each field in the file is separated by a comma, as noted in the above code.

Can anyone confirm to me the infamous ENTER that is being read at some point that I cannot detect? Or see some other error?

  • Is there any way to post the output as text? I can’t see it from my phone

  • You must have noticed you’re not reading all the odd customers, right? This is because you are consuming the file at two different points

  • You mean in fgets and fscanf?

  • Yes. I’m writing an answer detailing this

1 answer

2


For starters, how are you not touching the stdin, you don’t need to give a fflush in it.

Another thing: use fgets will cause the file reading pointer to be moved forward. Use fscanf soon after will not be able to use this data, as they have already been consumed!

How to solve this? There are some ways...

As the input is not available, I cannot try to run and check if really makes sense the code; I did what I could with the data provided

Return of fscanf

The function scanf and your sisters return a whole. What does this whole mean? Simple, how many arguments have been read. This function returns the amount of characters consumed by reading, or negative if it cannot read anything. You can find the documentation here.

I’m not sure about arguments like %*

This means that the function can be the parameter of the while. Generally speaking, assuming that your fscanf that is correct:

while (fscanf(arq, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo) > 0) { // tenta ler, se possível é um cliente válido
        printf("Cliente %d:\n", idx);
        idx++;
        // para cada linha capturada, atribui um valor a variável, para em seguida fazer a impressão
        // resto do seu código

sscanf, string reading

Another alternative is to keep the fgets and change the reading source. One of the family functions scanf is the sscanf:

  • scanf reads from the standard input
  • fscanf reads a given file
  • sscanf reads a string

The rest of the code continues identical, just change the fscanf therefore:

sscanf(linha, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\n", cpf, nome, cnh, endereco, contato, passaporte, idoneo);
  • Thank you very much!!!

  • @Angelo for nothing at all! The information I obtained through your text was partial, but I hope it was sufficient to shed light on your problem

Browser other questions tagged

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