getline, getwline, getdelim, getwdelim
來自 cppreference.com
< c | experimental | dynamic
| 定義於標頭檔案 <stdio.h> |
||
| (1) | (動態記憶體 TR) | |
| (2) | (動態記憶體 TR) | |
| (3) | (動態記憶體 TR) | |
| (4) | (動態記憶體 TR) | |
1) 行為類似於 getdelim(lineptr, n, '\n', stream)
2) 行為類似於 getwdelim(lineptr, n, L'\n', stream)
3) 從流
stream 中讀取字元,如同透過 fgetc,直到遇到 delimiter,將字元儲存在 *lineptr 指向的、大小為 *n 的緩衝區中,並自動增加其大小,如同透過 realloc,以適應整個輸入,包括分隔符,並新增一個空終止符。*lineptr 可以為 null,在這種情況下,*n 被忽略,並且 getline 分配一個新緩衝區,如同透過 malloc。如果 delimiter 的值超出 unsigned char 或 EOF 的範圍,則行為未定義。如果 *lineptr 不為 null,則如果 *lineptr 不是可以傳遞給 free 的指標,或者如果 *n 小於 *lineptr 指向的已分配記憶體的大小,則行為未定義。
作為動態記憶體 TR 中的所有函式,getline 僅在實現定義了 __STDC_ALLOC_LIB__ 並且使用者在包含 stdio.h 之前將 __STDC_WANT_LIB_EXT2__ 定義為整數常量 1 時才保證可用。
目錄 |
[編輯] 引數
| lineptr | - | 指向初始緩衝區或空指標的指標的指標 |
| n | - | 指向初始緩衝區大小的指標 |
| delimiter | - | 分隔符字元 |
| stream | - | 有效的輸入流,透過 fopen 開啟 |
[編輯] 返回值
儲存在緩衝區中的字元數,包括分隔符,但不包括空終止符。
錯誤時,返回 -1 並設定 stream 上的 feof 或 ferror。
[編輯] 注意
這些函式與其 POSIX 版本相同,只是允許(但不要求)在錯誤時設定 errno。
[編輯] 示例
執行此程式碼
#ifdef __STDC_ALLOC_LIB__ #define __STDC_WANT_LIB_EXT2__ 1 #else #define _POSIX_C_SOURCE 200809L #endif #include <stdio.h> #include <stdlib.h> void get_y_or_n(void) { char *response = NULL; size_t len; printf("Continue? [y] n: "); if((getline(&response, &len, stdin) < 0) || (len && response[0] == 'n')) { free(response); exit(0); } free(response); return; } int main(void) { get_y_or_n(); }
輸出
Continue? [y] n:
[編輯] 另請參閱
| 從檔案流獲取字元字串 (函式) | |
| (在 C11 中移除)(C11) |
從 stdin 讀取一個字串 (函式) |
| (C95) |
從檔案流中獲取一個寬字串 (函式) |
| 分配記憶體 (函式) |