Siberia
Siberia

Reputation: 3

C - Trying to determine number of elements in buffer filled by getline()

I have seen a lot of places saying that sizeof(buf)/sizeof(buf[0]) should work in determining the size of the array, but this does not work for me

char* buf = NULL;
size_t len;
len = 0;
while(getline(&buf,&len,stdin) >= 0 ){
    unsigned int i;
    size_t size= sizeof(buf)/sizeof(buf[0]);
    for (i = 0; i < size; i++){
        char* s;
        int pos;
        s = strtok(buf, " ");
        unsigned int j;
        for (j = 0; j < strlen(s); j++){
            doStuff();
        }

I want to deterine how many Strings are in buf so that I know how many times strtok() needs to be called in order to do something with each letter of the word.

Upvotes: 0

Views: 586

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84579

getline() returns the number of characters read. Use the return if you need the number of characters read. If you need the number of tokens parsed by strtok, keep an index and increment it.

len = 0;
ssize_t n = 0;    /* number of chars read by getline   */
size_t index = 0; /* number of tokens parsed by strtok */

while ((n = getline (&buf, &len, stdin)) >= 0 ) {
    ...
    char *s = buf;
    for (s = strtok (s, " "); s; s = strtok (NULL, " ")) {
        index++;
        ...
    }
    ...
    for (j = 0; j < index; j++){
        doStuff();
    }        

Note: buf is not preserved by strtok (it will have null-terminating characters embedded in it by strtok). If you need buf later, make a copy before calling strtok.

Upvotes: 2

milevyo
milevyo

Reputation: 2184

check the return value of getline()

from man-page

RETURN VALUE         top

   On success, getline() and getdelim() return the number of characters
   read, including the delimiter character, but not including the
   terminating null byte ('\0').  This value can be used to handle
   embedded null bytes in the line read.

   Both functions return -1 on failure to read a line (including end-of-
   file condition).  In the event of an error, errno is set to indicate
   the cause.

Upvotes: 1

Related Questions