C · Intermediário · Inglês · Técnico
fgets
Função que lê uma linha de um arquivo para um buffer, guardando no máximo n-1 caracteres e sempre terminando em nulo. Mantém o '\n' se couber.
Onde usar
É a forma segura de ler texto linha a linha. Remova o '\n' final com strcspn e compare o retorno com NULL para detectar o fim do arquivo.
Em código
char linha[128];
while (fgets(linha, sizeof linha, stdin)) {
linha[strcspn(linha, "\n")] = '\0';
puts(linha);
}Exemplos
Read the line with fgets and strip the newline.
Leia a linha com fgets e tire a quebra de linha.
fgets returns null at end of file.
O fgets devolve nulo no fim do arquivo.
Cuidado
Usar gets, que foi removida no C11 justamente por não ter como limitar o tamanho lido.
Antônimos
gets
Origem
Abreviação de file get string.