I'm working through The C Programming Language - 2nd Edition, trying to reason through the examples. I'm brand-new to C.
Much of the example code from the first chapter relies on getchar() to receive input. For instance, the following code, which returns the longest line of a block of text:
#include <stdio.h>
#define MAXLINE 1000
int max;
char line[MAXLINE];
char longest[MAXLINE];
int getline(void);
void copy(void);
int main()
{
int len;
extern int max;
extern char longest[];
max = 0;
while ((len = getline()) > 0)
if (len > max) {
max = len;
copy();
}
if (max > 0)
printf("%s", longest);
return 0;
}
int getline(void) {
int c, i;
extern char line[];
for (i = 0; i < MAXLINE-1 && (c=getchar()) != EOF && c != '\n'; ++i)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void copy(void) {
int i;
extern char line[], longest[];
i=0;
while ((longest[i] = line[i]) != '\0')
++i
}
Probably a simple answer, but what do I have to do to provide an external text file as input to this program?
EDIT: I've tried the following but am getting compilation errors:
#include <stdio.h>
#define MAXLINE 1000
int max;
char line[MAXLINE];
char longest[MAXLINE];
FILE *fp;
int getline(void);
void copy(void);
int main()
{
int len;
extern int max;
extern char longest[];
fp = fopen("./hello.txt", "r");
max = 0;
while ((len = getline()) > 0)
if (len > max) {
max = len;
copy();
}
if (max > 0)
printf("%s", longest);
fclose(fp);
return 0;
}
int getline(void) {
int c, i;
extern char line[];
extern FILE *fp;
for (i = 0; i < MAXLINE-1 && (c=fgetc(fp)) != EOF && c != '\n'; ++i)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void copy(void) {
int i;
extern char line[], longest[];
i=0;
while ((longest[i] = line[i]) != '\0')
++i;
}