E
Eric Sosman
Franken said:I'm trying to read a line of text from a file one at a time and pass the
linenumber and and a pointer to the text thereafter. I've got a pretty
good start on it. This compiles:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define my_file "text42.txt"
#define NUMBER 100
#define MAXFMTLEN 200
int main(void)
{
FILE *fp;
char *text;
unsigned long lineNumber;
int len;
if ((fp = fopen(my_file, "r")) == NULL ) {
fprintf(stderr, "can't open file\n");
exit(1);
}
while((len = getline(text, NUMBER)) > 0) {
printf("%c, %s", len, text);
}
fclose(fp);
return 0;
}
/* getline: get line into s, return length */
int getline(char *s, int lim)
{
char *p;
int c;
p = s;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
*p++ = c;
if (c == '\n')
*p++ = c;
*p = '\0';
return (int)(p - s);
}
// gcc ben5.c -Wall -o out
E:\gfortran\dan>gcc ben5.c -Wall -o out
ben5.c: In function `main':
ben5.c:24: warning: implicit declaration of function `getline'
ben5.c:15: warning: unused variable `lineNumber'
E:\gfortran\dan>
The warnings show where I'm stuck. How do I write getline to read from
my_file instead of stdin?
Change getline() so it takes a third parameter, the
FILE* stream to read from, and use getc(the_stream_param)
instead of getchar(). In the call to the new getline(),
pass the value of `fp' as the argument matching the new
parameter.
To get rid of the "implicit declaration" warning, either
insert a declaration of getline() someplace before it's first
called, or move the entire definition of getline() to a spot
before main().
To get rid of the "unused variable" warning, either get
rid of `lineNumber' or use it for something.
To get a useful warning about a potential problem in
getline(), crank up gcc's diagnostic level and call for an
optimization level that prompts the compiler to study the
usage patterns of variables. `-W -Wall -ansi -pedantic -O2'
is a reasonable starting point.
To avert criticism on grounds of style and portability,
change exit(1) to exit(EXIT_FAILURE).
To cure the error that will occur after you get the code
compiled and try to run it, see Question 7.1 in the comp.lang.c
Frequently Asked Questions (FAQ) list at <http://www.c-faq.com/>.
To forestall the accusation that you're re-inventing the
wheel, explain why you're writing your own getline() instead
of using fgets() and perhaps strlen(), both of which are
already written for you.