处理后的标准输入到标准输出

stdin to stdout after processing

我有一个实用程序可以通过将文件转换为替代文件格式来优化文件。如果不能缩小文件,我想退回原文件。

设计是用stdin输入,stdout输入输出。这是针对处理后的大小大于原始文件大小的情况。所有其他分支都被测试为工作。

  char readbuffer[65536];
  ssize_t readinbytes;
  while ((readinbytes = fread(readbuffer, sizeof(char), insize, stdin)) > 0) {
    if (fwrite(readbuffer, sizeof(char), readnbytes, stdout) != readnbytes) {
      fatal("can't write to stdout, please smash and burn the computer\n");
    }
  }

问题 这导致文件大小为 0

对了这个问题有一个奇怪的答案。本质上,我必须将 stdin 读入缓冲区 (inbuf),然后输出该缓冲区的内容。我没有得到输出的首要原因是多方面的。

  1. 首先我没能发现一个已经确定输入缓冲区是否小于输出缓冲区的分支

    if((readinbytes < outbuffersize) || force) {
        // inside this is where the code was...
    
  2. 看起来(因为 stdout 被用来写入)有一个部分包含未在匹配的 else 块中输出的日志语句。继承的代码格式非常糟糕,因此从未被采用。

    因为输出错误消息没有达到实用程序的目的(如果提供了有效的输入文件,则始终输出有效的输出文件)

解决方案stdin在程序开始读入inbuf

set_filemode_binary(stdout);
if (fwrite(inbuf, 1, readinbytes, stdout) != insize) {
    fprintf(stderr, "error writing to stdout\n");
    free(inbuf);
    exit(3);
}

勘误表(阅读stdin

unsigned char * inbuf = NULL;
size_t readinbytes;
long insize = 0;

// elsewhere...

// die if no stdin
insize = getFileSize(stdin);
if (insize < 0) {
    fprintf(stderr, "no input to stdin\n");
    exit(2);
}
// read stdin to buffer
inbuf = createBuffer(insize); // wrapper around malloc handling OOM
if ((readinbytes = fread(inbuf, sizeof(char), insize, stdin)) < 0) {
    fprintf(stderr, "error reading from stdin\n");
    free(inbuf);
    exit(3);
}

另外别忘了free(inbuf)

if(inbuf){ free(inbuf); }

我希望这对某人有所帮助。