All pastes #1715135 Raw Edit

strchr() text file lines in C

public c v1 · immutable
#1715135 ·published 2009-12-15 00:53 UTC
rendered paste body
/* null-terminate file lines in a single dynamically allocated memory * buffer via pointer arithmetic and standard C library calls.. * * compiles with gcc -Wall -ansi -pedantic strchrlines.c * * Updated: $Date: 2009/12/14 19:53:30 $ $Author: duper $ */#include<stdio.h>#include<stdlib.h>#include<strings.h>#include<unistd.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>voidvexit (const char *f){  perror (f);  exit (EXIT_FAILURE);}intmain (void){  register char *buf, *oldbuf, *p;  int fd = open ("yaml", O_RDONLY), re;  struct stat st;  if (fd < 0)    vexit ("open");  if ((re = fstat (fd, &st)) < 0)    vexit ("fstat");  oldbuf = buf = malloc (st.st_size + 1);  if (read (fd, buf, st.st_size) < 0)    vexit ("read");  buf[st.st_size] = '\0';  do    {      if (!*buf)        break;      if (!(p = strchr (buf, '\n')))        break;      *p = 0;      puts (buf);      buf = 1 + p;    }  while (1);  exit (EXIT_SUCCESS);}