C - 尝试确定由 getline() 填充的缓冲区中的元素数

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

我看到很多地方说 sizeof(buf)/sizeof(buf[0]) 应该可以确定数组的大小,但这对我不起作用

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();
        }

我想确定 buf 中有多少个字符串,以便我知道需要调用多少次 strtok() 才能对单词的每个字母执行某些操作。

getline()return读取的字符数。如果需要读取的字符数,请使用 return。如果您需要 strtok 解析的标记数,请保留 index 并递增它。

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();
    }        

注意: buf 不是strtok 保留(它将有 null-terminating strtok 嵌入其中的字符)。如果您以后需要 buf,请在调用 strtok 之前复制一份。

检查 getline()

的 return 值

来自手册页

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 ('[=10=]').  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.