Skip to content

Instantly share code, notes, and snippets.

@bencz
Created November 17, 2013 18:16
Show Gist options
  • Save bencz/7516289 to your computer and use it in GitHub Desktop.
Save bencz/7516289 to your computer and use it in GitHub Desktop.
read a line in C
#include <stdio.h>
#include <string.h>
int fgetline(FILE *fp, char s[], int lim)
{
char *t;
int c, len=lim;
t = s;
while (--lim>1 && (c=getc(fp)) != EOF && c != '\n')
{
*s++ = c;
if (c == '\n')
*s++ = c;
else if (lim == 1)
{
*s++ = '\n';
fprintf(stderr, "WARNING. fgetline: Line too long, splitted.\n");
}
}
*s = '\0';
return s - t;
}
main()
{
FILE *fp;
char buff[255];
fp = fopen("input.txt", "r");
fgetline(fp, buff, 20);
printf("%s\r\n", buff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment