c - 寻找改进的想法

标签 c

海湾合作委员会 4.4.4 c89

有更好的方法吗?

我有以下代码可以从文本文件中读取。文本文件包含如下行:

4 5 6 1 5 7 5 9 5 3 5 7 8 3 2 3 
7 2 3 4 5 3 7 9 3 2 5 6

我只给出了 2 行示例,但可以有更多行并且每行的长度都不同。

我需要做的是将数字放入缓冲区,以便我可以对它们进行分析。这很容易。

但是,我正在寻找一种不会覆盖每行缓冲区的解决方案。所以我的结果缓冲区应该包含以下内容:

4 5 6 1 5 7 5 9 5 3 5 7 8 3 2 3 7 2 3 4 5 3 7 9 3 2 5 6

所以我使用 fgets 读取行,并将该行传递给我的分析函数。

但是,我需要 for 循环中的增量值从最后一个结束的地方开始。

我已将 device_buff 设置为静态。那安全吗。我不热衷于在函数内部使用静态变量,因为它们不是线程安全的并且构成全局变量。

int g_load_devices_numbers(void)
{
    fget(line_read, DEVICE_SIZE, fp) == NULL) {
        analyse_device_numbers(line_read);   
    }
}

static void analyse_device_numbers(const char * const device_line)
{
    size_t i = 0;
    static char device_buff[1024] = {0};
    static size_t device_counter = 0;
    /* Start inserting the last index */
    static size_t buff_counter = 0;

    /* copy each number into the char array
     * only copy up to the 'return' as fgets always inserts one */
    for(i = 0; device_line[i] != '\n'; i++, buff_counter++) {
        device_buff[buff_counter] = device_line[i];
        /* Only count numbers and not spaces */
        if(isspace(device_buff[buff_counter]) == 0) {
            device_counter++;
        }
    }

    /* nul terminate the vote buffer */
    device_buff[buff_counter] = '\0';

}

非常感谢您的任何建议,

最佳答案

不,在这里为 device_buff 使用静态缓冲区是不安全的。不是因为缓冲区本身,而是因为它有一个未检查的有限大小(1024 项)。

将必须存储数据的缓冲区和缓冲区的长度作为输入参数提供给 analyse_device_numbers 会更安全。仍然必须检查长度,以避免在提供的缓冲区的最后一个单元格之后写入,并且您必须选择一些错误管理约定(例如在发生缓冲区溢出时从 analyse_device_numbers 返回 -1)。

要始终在同一个目标缓冲区中写入,通常的技巧是移动提供的缓冲区的开头(考虑到已存储的项目)并将总长度减少相同的数量。这可以在调用 g_load_device_numbers 的外部循环中完成。

关于c - 寻找改进的想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062685/

相关文章:

c - fread 函数未存储到缓冲区中

c - R 的 hier.part() 取决于预测器顺序

从 C 文件更改头文件中结构变量中的 char 数组会弄乱数组

c - 我的代码有什么问题,我希望以 int 形式打印输出,但似乎没有?

c - 除了/dev/input/eventx 之外,是否有更高级别(字符?)的方式来访问 Linux 键盘?

c++ - 进程和线程相关问题

c - 对文件 C 中的行进行排序

c++ - CUDA __device__ 未解析的外部函数

c - 下面的C代码会生成多少个进程和线程?

无法释放内存(断言错误)