如何在C中读取无限字符 [英] How to read unlimited characters in C

查看:19
本文介绍了如何在C中读取无限字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不指定大小的情况下将无限个字符读入 char* 变量?

How to read unlimited characters into a char* variable without specifying the size?

例如,假设我想读取也可能需要多行的员工的地址.

For example, say I want to read the address of an employee that may also take multiple lines.

推荐答案

您必须先猜测"您期望的大小,然后使用 malloc 分配一个那么大的缓冲区.如果结果太小,您可以使用 realloc 将缓冲区的大小调整为更大一些.示例代码:

You have to start by "guessing" the size that you expect, then allocate a buffer that big using malloc. If that turns out to be too small, you use realloc to resize the buffer to be a bit bigger. Sample code:

char *buffer;
size_t num_read;
size_t buffer_size;

buffer_size = 100;
buffer = malloc(buffer_size);
num_read = 0;

while (!finished_reading()) {
    char c = getchar();
    if (num_read >= buffer_size) {
        char *new_buffer;

        buffer_size *= 2; // try a buffer that's twice as big as before
        new_buffer = realloc(buffer, buffer_size);
        if (new_buffer == NULL) {
            free(buffer);
            /* Abort - out of memory */
        }

        buffer = new_buffer;
    }
    buffer[num_read] = c;
    num_read++;
}

这只是我的想法,可能(阅读:可能)包含错误,但应该给你一个好主意.

This is just off the top of my head, and might (read: will probably) contain errors, but should give you a good idea.

这篇关于如何在C中读取无限字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆