Using the getline () function in C with MinGW
I created a code for a library collection using Linux/GNU, and there it is working perfect. However, I need the code to compile on Windows using GCC, and I 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 code snippets involved in the 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, ®num, &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 using a # define _GNU_SOURCE but it didn't work
1 answers
Has two possibilities, and in both the idea is to use one of the several implementations of the function getline
that already exist:
- https://dev.w3.org/libwww/Library/src/vms/getline.c
- https://stackoverflow.com/a/47229318/6087092
- https://github.com/filosganga/libwurfl/blob/master/src/utils/getline.c
In the first scenario you only create the function if you have to compile in windows environment, testing with #ifdef
for 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
code and give it another name. This will never collide with one that is already set:
ssize_t obterlinha(char **lineptr, size_t *n, FILE *stream) {
//resto do código aqui
}