aboutsummaryrefslogtreecommitdiff
path: root/ch1/1-19_reverse-lines.c
diff options
context:
space:
mode:
authorzlg <zlg@zlg.space>2013-02-13 20:48:44 -0600
committerzlg <zlg@zlg.space>2013-02-13 20:48:44 -0600
commit5018e06c580dd21c958ec1672c26a3448faf0c55 (patch)
treecebbb56dad0a6b821cad3712c7977f6f9b0086ab /ch1/1-19_reverse-lines.c
parentFix 1-09's solution (diff)
downloadknr-5018e06c580dd21c958ec1672c26a3448faf0c55.tar.gz
knr-5018e06c580dd21c958ec1672c26a3448faf0c55.tar.bz2
knr-5018e06c580dd21c958ec1672c26a3448faf0c55.tar.xz
knr-5018e06c580dd21c958ec1672c26a3448faf0c55.zip
Add license file, reorganize project
Diffstat (limited to 'ch1/1-19_reverse-lines.c')
-rw-r--r--ch1/1-19_reverse-lines.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/ch1/1-19_reverse-lines.c b/ch1/1-19_reverse-lines.c
new file mode 100644
index 0000000..d87b625
--- /dev/null
+++ b/ch1/1-19_reverse-lines.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+
+#define MAXLINELENGTH 9001
+
+int get_line(char s[], int limit) {
+ int c, i;
+
+ for (i = 0; i < limit && (c = getchar()) != EOF && c != '\n'; ++i) {
+ s[i] = c;
+ }
+
+ s[i] = '\0';
+
+ /* If I don't include this check, I can't handle blank lines */
+ if (c == EOF && i == 0) {
+ return -1;
+ } else {
+ return i;
+ }
+
+}
+
+/* Directly reverse a line's contents. */
+void reverse(char input[], int size) {
+ int tmp;
+ int i = 0;
+ size--;
+
+ /* If len and i are the same, then there's no reason to proceed */
+ while (size > i) {
+ // Store the first character in a temporary spot...
+ tmp = input[i];
+
+ // ... and swap!
+ input[i] = input[size];
+ input[size] = tmp;
+
+ // Bring our numbers closer together
+ ++i;
+ --size;
+ }
+}
+
+int main(void) {
+ // An int and a string to store each line's data in
+ int line_len;
+ char buffer[MAXLINELENGTH];
+
+ while ((line_len = get_line(buffer, MAXLINELENGTH)) != -1) {
+ reverse(buffer, line_len);
+ printf("%s\n", buffer);
+ }
+ return 0;
+}