lisp9000@[EMAIL PROTECTED]
wrote:
> I was wondering the best way to define and loop through a character
> array. Most lines of the file I am processing are 80 characters long
> but when an error occurs in the client which created the log sometimes
> they can be much longer so what's the best way to determine the array
> and define it?
>
> char s[80];
>
> vs
>
> #define MAX 100
> char s[MAX];
The second way is preferable, as it allows you to refer to the size via a
name and if you need to change the size you only need to change it in one
place.
> int i;
> for (i=0; i < sizeof(s); i++) { printf("%s", s[i]);)
This is broken code, sorry.
1. s[n] yields a single char, but printf's '%s' directive expects a
NUL-terminated char string (or, rather, a pointer to one).
2. 'sizeof object' yields the size of the object in bytes. This has
nothing
to do with the number of characters in a string, for that you need the
strlen() function.
3. If you want to look at each character in turn, you need to loop from
zero
to strlen(s). Note: this assumes that 's' actually is a NUL-terminated
string.
> I can read each line of my log file using fgets, now should I use
> fixed arrays like:
>
> char s[80];
> FILE *fp;
>
> fp = fopen("foo.txt","r");
> fgets(s,sizeof(s),fp);
Why not? It limits you to 80 characters per line, but using appropriate
error handling that might actually be okay. Tackle one problem at a time.
Note btw that passing an array to a function actually p***** a pointer to
the first element.
> Or would it be better assign a pointer value for the first char each
> line:
>
> char *s[80];
This is an array of 80 pointers, what would you want to do with that? The
only thing it would be useful for would be to store 80 lines, but that's
not what you want.
> fgets(*s,sizeof(s),fp);
This p***** the first pointer in an otherwise uninitialised array to
fgets()
and the size of the array in bytes as maximum number of characters to
store. Neither brings you closer to what you probably want to achieve.
Rather, if you want to read lines of varying length, you should research
memory handling, the functions you will be able to make use of are malloc,
realloc, free, strcat, any C book should actually address those somewhere.
Once you learned that, you can call fgets() multiple times to read the
whole line in chunks and append them to each other.
Good luck!
Uli
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|