Use of the getline() function in C with Mingw

Asked

Viewed 104 times

0

I created code for a library collection using Linux/GNU, and it’s working perfectly. However, I need to Compile code on Windows using GCC, and wanted to know if there is a method to use this function or if there is a simple way to replace it. Here are the snippets of code involved in questioning:

FILE * arquivo;
Livro * acervo;
int indice = 0, i;    
int ultimo_regnum = 0;

char * linha = NULL;
size_t tamanho = 0;
ssize_t check;

while ((check = getline(&linha, &tamanho, arquivo)) != -1) {
    sscanf(linha, "%[^||]||%[^||]||%[^||]||%[^||]||%[^||]||%hd||%hd||%hd||%d||%f", titulo, editora, autor, genero, encadernacao, &ano, &edicao, &paginas, &regnum, &preco);
    //printf("%s\n%s\n%s\n%s\n%s\n%hd\n%hd\n%hd\n%d\n%f\n", titulo, editora, autor, genero, encadernacao, ano, edicao, paginas, regnum, preco);
    strcpy(acervo[indice].titulo, titulo);
    strcpy(acervo[indice].editora, editora);
    strcpy(acervo[indice].autor, autor);
    strcpy(acervo[indice].genero, genero);
    strcpy(acervo[indice].encadernacao, encadernacao);
    acervo[indice].ano = ano;
    acervo[indice].edicao = edicao;
    acervo[indice].paginas = paginas;
    acervo[indice].regnum = regnum;
    acervo[indice].preco = preco;
    indice++;
    ultimo_regnum = regnum;
    acervo = (Livro *)realloc(acervo, sizeof(Livro) * (indice + 1));
    if (acervo == NULL){
        printf("Erro ao alocar memoria.\n");
        exit(1);
    }
}

fclose(arquivo);

}

I tried to use a #define _GNU_SOURCE but it didn’t work

  • In this case it seems to me that the best solution is to use one of the implementations that are out there.

  • Which implementation would be the best in this case and how it would be composed according to the variables used in getline?

1 answer

1


It has two possibilities, and in both the idea is to use one of several implementations of the function getline that already exist there:

In the first scenario you only create the function if you have to compile in windows environment, testing with #ifdef for the macro _WIN32:

#ifdef _WIN32

ssize_t getline(char **lineptr, size_t *n, FILE *stream) {
    //resto do código aqui
}

#endif

Alternatively you can simply create your own function with the getline and give it another name. It will never collide with one that is already defined:

ssize_t obterlinha(char **lineptr, size_t *n, FILE *stream) {
    //resto do código aqui
}

Browser other questions tagged

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