用c实现getline
时间: 2024-05-15 18:17:00 浏览: 60
以下是用C语言实现getline函数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
char *getline(void) {
char *line = NULL;
char ch;
int len = 0;
int size = 1;
// allocate memory for the line
line = (char *) malloc(size * sizeof(char));
if (line == NULL) {
printf("Error: unable to allocate memory for the line\n");
exit(1);
}
// read characters from stdin until new line or end of file
while ((ch = getchar()) != '\n' && ch != EOF) {
// resize the line if necessary
if (len >= size) {
size *= 2;
line = (char *) realloc(line, size * sizeof(char));
if (line == NULL) {
printf("Error: unable to resize memory for the line\n");
exit(1);
}
}
// add the character to the line
line[len++] = ch;
}
// add null terminator to the line
line[len] = '\0';
return line;
}
int main() {
char *line;
printf("Enter a line of text: ");
line = getline();
printf("The line you entered is: %s\n", line);
free(line);
return 0;
}
```
这个getline函数实现了从标准输入读取一行字符串,并将其存储在动态分配的内存中。如果在读取过程中需要重新分配内存,则使用realloc函数来增加内存大小。函数返回一个指向动态分配的内存的指针,需要在使用完后调用free函数来释放内存。
阅读全文