Reading only odd records

Asked

Viewed 82 times

1

Initially, I had to create a program to save data from a struct to a file. The struct is as follows::

typedef struct
{
    char nome[30];
    int matricula;
    char conceito;
} TipoAluno;

I made the program in a way that saved the data in the file as follows:

Nome: Maria da Silva
Matricula: 2016010203
Conceito: A

Nome: Joana Oliveira
Matricula: 2015020301
Conceito: A

Nome: Joao Souza
Matricula: 2017050401
Conceito: B

Nome: Paulo Silveira
Matricula: 2015020301
Conceito: A

Nome: Hugo Fernandes
Matricula: 2014050102
Conceito: C

After this exercise, I was asked to create another program to read only the odd records of this file. However, I was in doubt. It is possible to use the index rating [i] to manipulate the contents of the file and write the code or it is only possible using the file information (for example: lines or characters)?

I made the following code:

int main()
{
    FILE *arq;
    char c;
    int contaLinha = 1;

    arq = fopen("Teste.txt", "r");
    if(arq == NULL)
    {
        printf("Erro ao abrir o arquivo.");
        exit(1);
    }

    while(!feof(arq))
    {
        c = fgetc(arq);
        if(c == '\n')
            contaLinha++;

        if(contaLinha == contaLinha || contaLinha + 8)
            printf("%c", c);
    }

    fclose(arq);

    return 0;
}

I thought this way because, every 8 lines, there is an odd record. However, it is necessary to create a stop condition to stop reading the even records. How could this stop be?

1 answer

1


You can assume that it is the end of a record every time a blank line is found:

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

#define NOME_ARQUIVO     "Teste.txt"
#define LINHA_MAX_TAM    (100)

int main( void )
{
    FILE * arq = NULL;
    int contaRegistro = 1;
    char linha[ LINHA_MAX_TAM +1 ] = {0};

    arq = fopen( NOME_ARQUIVO, "r" );

    if(!arq)
    {
        printf("Erro ao abrir o arquivo '%s' para leitura.\n", NOME_ARQUIVO );
        return 1;
    }

    /* Para cada linha do arquivo texto... */
    while( fgets( linha, LINHA_MAX_TAM, arq ) )
    {
        /* Remove caracteres de controle CR e/ou LF do final da linha */
        linha[ strcspn( linha, "\r\n" ) ] = '\0';

        /* Exibe linhas somente dos registros impares */
        if( contaRegistro % 2 )
            printf( "%s\n", linha );

        /* Assume que uma linha vazia eh o final de um registro */
        if( strlen(linha) <= 0 )
            contaRegistro++;
    }

    fclose(arq);

    return 0;
}

Exit:

Nome: Maria da Silva
Matricula: 2016010203
Conceito: A

Nome: Joao Souza
Matricula: 2017050401
Conceito: B

Nome: Hugo Fernandes
Matricula: 2014050102
Conceito: C

Browser other questions tagged

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