我有一个实用程序,可以通过将文件转换为备用文件格式来优化文件。如果它不能使文件变小,我希望返回原始文件。
设计是使用stdin
in和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),然后输出该缓冲区的内容。我没有得到任何输出的主要原因是多方面的。
首先,我未能发现一个已经确定输入缓冲区是否小于输出缓冲区的分支
if((readinbytes < outbuffersize) || force) { // inside this is where the code was...
看起来(因为 stdout 用于写入)有一个部分包含一条日志语句,该语句未在匹配的
else
block 中输出。继承的代码格式非常糟糕,因此从未被采用。由于输出错误消息不能满足该实用程序的目的(如果提供了有效的输入文件,则始终输出有效的输出文件)
解决方案(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); }
我希望这对某人有帮助。
关于c - 处理后 stdin 到 stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935325/