Win32下在stdin上使用fread()的问题 [英] Problems using fread() on stdin under win32

查看:309
本文介绍了Win32下在stdin上使用fread()的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Win32下以二进制模式从stdin解析数据. 我的代码要做的第一件事是在开头检查4byte标头:

I'm trying to parse data from stdin in binary mode under Win32. The first thing my code does is to check for a 4byte header at the beginning:

int riff_header;
fread(&riff_header, sizeof(riff_header), 1, ifp);
//  'RIFF' = little-endian
if (riff_header != 0x46464952) {
    fprintf(stderr, "wav2msu: Incorrect header: Invalid format or endianness\n");
    fprintf(stderr, "         Value was: 0x%x\n", riff_header);
    return -1;
}

stdin在读取之前已切换到二进制模式:

stdin has been switched to binary mode before reading from it:

if (*argv[argc-1] == '-') {
    fprintf(stderr, "Reading from stdin.\n");
    infile = stdin;
    // We need to switch stdin to binary mode, or else we run
    // into problems under Windows
    freopen(NULL, "rb", stdin);
}

此代码在Linux下可以正常工作,但是在Win32(特别是Windows XP)上,fread似乎只能读取一个字节,从而导致评估失败. 示例:

This code works fine under Linux, however on Win32 (specifically Windows XP), the fread only seems to read a single byte and thus cause the evaluation to fail. Example:

> ffmeg.exe -i ..\test.mp3 -f wav pipe:1 2> nul |..\foo.exe -o test.bin -
Reading from stdin.
foo: Incorrect header: Invalid format or endianness
     Value was: 0x4

我在做什么错了?

推荐答案

http ://pubs.opengroup.org/onlinepubs/009695399/functions/freopen.html 我发现了以下内容:

如果filename是一个空指针,则freopen()函数应尝试执行以下操作: 将流的模式更改为mode指定的模式,就像 当前使用了与该流关联的文件名. 在这种情况下,与流关联的文件描述符不需要 如果对freopen()的调用成功,则将其关闭.它是 实现定义的,允许哪些模式更改(如果有), 在什么情况下.

If filename is a null pointer, the freopen() function shall attempt to change the mode of the stream to that specified by mode, as if the name of the file currently associated with the stream had been used. In this case, the file descriptor associated with the stream need not be closed if the call to freopen() succeeds. It is implementation-defined which changes of mode are permitted (if any), and under what circumstances.

也许您应该检查所使用的编译器和库是否允许模式更改(从文本更改为二进制).您正在使用哪个编译器?

Maybe you should check if the change of mode (from text to binary) is allowed by the compiler and libraries you are using. Which compiler are you using?

更新/摘要

使用MinGW,您可以调用setmode()来切换标准输入流的模式. 您应该将模式设置为_O_BINARY,该模式在fcntl.h中定义. 有关更多信息,请参见 http://gnuwin32.sourceforge.net/compile.html

Using MinGW you can call setmode() to switch the mode of the stdin stream. You should set the mode to _O_BINARY, which is defined in fcntl.h. For more information see e.g. http://gnuwin32.sourceforge.net/compile.html

这篇关于Win32下在stdin上使用fread()的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆