Created
June 2, 2025 21:34
-
-
Save jftuga/dab3f923e924e9d43d50c0ea8f0477ea to your computer and use it in GitHub Desktop.
chomp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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