getline函数实现
时间: 2023-09-05 21:12:40 浏览: 127
getline()函数是一个常用的C语言函数,用于从输入流中读取一行字符并存储到字符数组中。下面是getline()函数的实现代码:
```
int getline(char s[], int lim) {
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i = c;
if (c == '\n') {
s[i = c;
i++;
}
s[i = '\0';
return i;
}
```
该函数接受两个参数,一个是字符数组s,用于存储读取到的字符;另一个是整数lim,表示字符数组s的最大长度。函数会逐个读取输入的字符,直到达到lim的上限、遇到文件结束符EOF或遇到换行符'\n'为止。在读取过程中,将字符存储到字符数组s中,并在数组末尾添加'\0'作为字符串的结束符。函数返回值为实际读取到的字符数(不包括结束符)。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [【C】getline()函数实现](https://blog.csdn.net/ww1473345713/article/details/51474553)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [getdelim:C语言中的getdelim()和getline()实现](https://download.csdn.net/download/weixin_42101384/16632127)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [Python linecache.getline()读取文件中特定一行的脚本](https://download.csdn.net/download/weixin_38516491/13769977)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文