Skip to content

Instantly share code, notes, and snippets.

@jftuga
Created June 2, 2025 21:34
Show Gist options
  • Save jftuga/dab3f923e924e9d43d50c0ea8f0477ea to your computer and use it in GitHub Desktop.
Save jftuga/dab3f923e924e9d43d50c0ea8f0477ea to your computer and use it in GitHub Desktop.
chomp
/*
* A C implementation that mimics Perl's 'chomp' functionality.
* Reads from standard input and outputs all characters except the trailing newline.
* Preserves internal newlines but removes only the final newline if present.
* Compile with: gcc -O2 -o chomp chomp.c
*/
#include <stdio.h>
int main(void) {
int c, prev_c = EOF;
/* Read character by character from stdin */
while ((c = getchar()) != EOF) {
/* If we have a previous character, output it */
if (prev_c != EOF) {
putchar(prev_c);
}
prev_c = c;
}
/* Output the last character only if it's not a newline */
if (prev_c != EOF && prev_c != '\n') {
putchar(prev_c);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment