有效的 stdin 读取 C 编程

2023-12-03

任何人都可以帮助我优化读取标准输入的代码。这就是我现在所拥有的:

unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}

问题:您正在读取二进制数据还是文本数据stdin?如果是文本,你为什么使用unsigned char?

一些忠告:

  1. 放下所有演员malloc and realloc;它们不是必需的,而且会使代码变得混乱;
  2. 而不是反复调用getchar, use fread or fgets(取决于您正在阅读二进制还是文本);
  3. 请记住realloc可能会返回 NULL,因此您希望将结果分配给临时值,否则您将失去原始指针并导致内存泄漏;
  4. 为每个输入块使用静态分配的缓冲区;
  5. Use sizeof关于对象,而不是类型;它更干净一点,并且可以在类型发生变化时保护您(例如,T *p = malloc(sizeof *p * number_of_elements);.

假设您打算使用无符号字符的清理版本:

#define inputBufSize 1024

unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufSize = 0;
unsigned char inputBuffer[inputBufSize];
size_t bytesRead = 0;

while ((bytesRead = fread(
    inputBuffer,            // target buffer
    sizeof inputBuffer,     // number of bytes in buffer
    1,                      // number of buffer-sized elements to read
    stdin)) > 0)
{
  unsigned char *tmp = realloc(msg, inputMsgBufSize + bytesRead));
  if (tmp)
  {
    msg = tmp;
    memmove(&msg[inputMsgBufSize], inputBuffer, bytesRead);
    inputMsgBufSize += bytesRead;
  }
  else
  {
    printf("Ran out of memory\n");
    free(msg);
    break;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有效的 stdin 读取 C 编程 的相关文章

随机推荐