2015-01-21 68 views
-1

我已經編寫了一個類似的函數,它是調用get_next_line,並在每次調用它返回一個字符串到當前行。但是我發現一個人很容易做到,而且完全無法理解他的代碼。我很想你們的幫助。我不明白這個代碼背後的邏輯

char *get_next_line(const int fd) 
{ 
    static int last = 1; 
    static int rd = 0; 
    static int i = 0; 
    static char *res = NULL; 
    static char buff[READ_MAX]; 

    if (buff[my_length(buff) - rd] == '\0') 
    { 
     if ((rd = read(fd, buff, READ_MAX)) <= 0) 
     return (res = (last-- && buff[my_length(buff) - rd - 1] != 10) ? res : NULL); 
     buff[rd] = '\0'; 
    } 
    if ((res = (i == 0) ? malloc(sizeof(*res) * READ_MAX + 1) : 
     my_realloc(res, sizeof(*res) * READ_MAX + 1)) == NULL) 
    return (NULL); 
    while (buff[my_length(buff) - rd] && buff[my_length(buff) - rd] != '\n') 
    res[i++] = buff[my_length(buff) - rd--]; 
    res[i] = '\0'; 
    if (buff[my_length(buff) - rd] == '\n') 
    { 
     i = 0; 
     rd--; 
     return (res); 
    } 
    return (get_next_line(fd)); 
} 

舉例來說,我不明白:

return (res = (last-- && buff[my_length(buff) - rd - 1] != 10) ? res : NULL); 

什麼的 '?'和':'是什麼意思?這是否意味着'?'之前的狀況返回res或NULL?

這是一個相當大的問題,但感謝您的幫助。

PS:在頭文件中,READ_MAX的值爲5。

+2

聽起來很合理。我也不明白它,這是一個吝嗇鬼。 – 2015-01-21 11:08:29

+0

我不會說「令人驚訝的容易」,它很難閱讀,完全沒有註釋,而且代碼結構幾乎完全隱藏。嘗試從這段代碼開始,然後簡化它,每行只執行一個操作。希望結構會彈出。 – Gauthier 2015-01-21 11:51:46

+0

'my_length()'函數過於頻繁,恕我直言。它有什麼作用 ? – wildplasser 2015-01-21 11:58:14

回答

0
return (res = (last-- && buff[my_length(buff) - rd - 1] != 10) ? res : NULL); 

這裏?:是一個三元運算符。如果?之前的表達式結果爲TRUE,則在執行:之後,緊接在?之後的值被執行,否則執行後者。

這是一樣的

if((last--) && (buff[my_length(buff) - rd - 1] != 10)) 
{ 
    res = res; 
} 
else 
{ 
    res = NULL; 
} 
return res; 
1
What does the '?' and ':' mean? 

這在C稱爲Ternary operator。一個例子是在這裏,

result = a > b ? x : y; 

相當於,

if (a > b) { 
    result = x; 
} else { 
    result = y; 
} 

現在關於讓你理解的代碼發佈,最如果它是標準的函數調用,如read()malloc()realloc()sizeof(),串終止與\0等,我建議通過每一行一個一個會真正幫助你學習。

0

這是三元操作符。參考link

(if the condition is true)?it will execute:or else it will execute; 

在這種情況下

(res = (last-- && buff[my_length(buff) - rd - 1] != 10) ? res : NULL); 

如果條件(res = (last-- && buff[my_length(buff) - rd - 1] != 10)爲真,那麼res將返回。如果條件爲假,則返回NULL

它等於這個。

if ((res = (last-- && buff[my_length(buff) - rd - 1]) != 10) 
{ 
    return (res=res); 
} 
else 
{ 
    return (res=NULL); 
}