[英]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
),然后輸出該緩沖區的內容。 我沒有輸出的首要原因是多方面的。
首先,我沒有發現一個分支,該分支已經確定輸入緩沖區是否小於輸出緩沖區
if((readinbytes < outbuffersize) || force) { // inside this is where the code was...
看起來(因為使用 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); }
我希望這可以幫助別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.