Skip to content

Instantly share code, notes, and snippets.

@schwern
Created December 11, 2016 00:16
Show Gist options
  • Save schwern/ae3250fdd2b21277c9987c65a49d13e7 to your computer and use it in GitHub Desktop.
Save schwern/ae3250fdd2b21277c9987c65a49d13e7 to your computer and use it in GitHub Desktop.
fgets vs fgetc, strlen vs strcpsn for stripping newlines off input lines
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int read_line_fgetc(FILE *fp, char *line, int line_size){
int c;
int i = 0;
while( (c = fgetc(fp)) > 0) {
if( (char)c == '\n' ) {
break;
}
line[i] = (char)c;
i++;
if( i > line_size ) {
break;
}
}
line[i] = '\0';
return i == 0 ? -1 : i;
}
int read_line_fgets_strcpsn( FILE *fp, char *line, int line_size ) {
if( fgets(line, line_size, fp) == NULL ) {
return -1;
}
line[strcspn(line, "\r\n")] = 0;
return 1;
}
int read_line_fgets( FILE *fp, char *line, int line_size ) {
if( fgets(line, line_size, fp) == NULL ) {
return -1;
}
size_t len = strlen(line);
if( line[len-1] == '\n' ) {
line[len-1] = '\0';
if( line[len-2] == '\r' ) {
line[len-2] = '\0';
}
}
return (int)len;
}
int main(int argc, char *argv[]) {
if( argc < 2 ) {
exit(1);
}
FILE *fp = fopen(argv[1], "r");
char line[1024];
while( read_line_fgets_strcpsn(fp, line, 1024) > 0 ) {
puts(line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment