Linux和Windows常见的C/C ++文件读取 [英] File reading in C/C++ common for Linux and Windows

查看:72
本文介绍了Linux和Windows常见的C/C ++文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从文件中读取二进制数据,我编写了如下代码,

To read binary data from a file, I have written a code as follows,

int fd = open(sFilePath, O_RDONLY, 0); //BINARY READ OPERATION
int iBytesToRead = 100;
unsigned char* pBuffer = new unsigned char[iBytesToRead];
while(true)
{
    int iReadBytes = read(fd, pBuffer, iBytesToRead);
    if( !iReadBytes ) break;
}



在Windows(VC9)中,在"while"循环内,第一次在"iBytesToRead"中传递的值(大于63!)都将"read()"返回"63".然后稍后返回"0"(从循环中断开).
但是文件大小远不止于此,因为相同文件的相同代码在Linux(gcc)中可以正常工作.

这有什么问题吗?或者我有什么遗漏吗?

谢谢&问候,
Aniket A. Salunkhe



In Windows (VC9), within ''while'' loop, first time it ''read()'' returns ''63'' whatever value (more than 63!) is passed in ''iBytesToRead''. And later on it returns ''0'' (break from the loop).
But file size is much more than that, as same code for same file works properly in Linux (gcc).

Is there any wrong in this or Am I missing something in it?

Thanks & Regards,
Aniket A. Salunkhe

推荐答案

我没有发现任何严重的错误.但是你应该使用
I did not see anything serious wrong. But you should use
int fd = open(sFilePath, O_RDONLY | O_BINARY, 0);


确保文件以二进制模式打开,因为默认的Windows fmodeO_TEXT.

在二进制模式下,然后read应该返回iBytesToRead,而不仅仅是在文件结尾之前.


to ensure that the file is opened in binary mode, because the default Windows fmode is O_TEXT.

With binary mode, read should then return iBytesToRead while not just before the end of file.


这篇关于Linux和Windows常见的C/C ++文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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