Exercise 2-2 (getline, copy)

Chapter_2     Exercise_2-1     Leap_year atoi     Exercise_2-3







Exercise 2-2     K&R, p. 42


Exercise 2-2. Write a loop equivalent to the for() loop above [K&R, p. 41, from getline(), Chapter_1, Sec. 1.9] without using && or ||.




copy.c         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define MAXLINE 1000 // maximum input line size

int getLine(char line[], int maxline); // getline() is defined by stdio.h
// int getLine(char [], int); // alternative declaration

int main()
{
int len; // current line length
char line[MAXLINE]; // current input line

while((len = getLine(line, MAXLINE)) > 0)
{ // line containing only '\n' not empty
printf("%s", line);
if (line[len-1] != '\n')
{putchar('\n');} // line may not end with '\n'
}

return 0;
}

// getLine(): read a line into s[], return length
int getLine(char s[], int lim)
{
int c = EOF; // initialize
int i;
// getchar() is only executed if (i < (lim-1)):
for (i = 0; i < (lim-1); i++)
{ // from 0 to lim-2; s[lim-2]='\n' or not, s[lim-1]='\0'
c = getchar();
if (c == EOF) // i < (lim-1), getchar() executed
{
s[i] = '\0'; // the null character ends a string
return i;
}
if (c == '\n') // i < (lim-1), getchar() executed
{
s[i] = c; // '\n'
i++;
s[i] = '\0'; // the null character ends a string
return i;
}
s[i] = c;
} // here c != EOF && c != '\n'

s[i] = '\0'; // i == (lim-1)
return i;
}
/*
gcc copy.c -o copy
./copy < copy.c // source file

./copy < copy.c > copy2.c
gcc copy2.c -o copy2
./copy2 < copy2.c

./copy < copy // binary file
./copy < copy > copy2
./copy2 < copy2.c // some run-time error

rm copy2.c copy2 // clean
*/









Chapter_2     Exercise_2-1     Leap_year BACK_TO_TOP atoi     Exercise_2-3



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo