【发布时间】:2011-10-31 22:20:07
【问题描述】:
我的学校给了我一个小库来做一些项目。这个库是用 linux 编写的,所以我试图改变一些东西来使用我的 MinGW 编译器。一个特定的程序用于读取给定 URL 的文件。我不得不将 stat 更改为 _stat 以使其正常工作。打开文件工作正常,但 _stat 似乎返回不正确的值。我将在下面包含相关代码:
#ifdef WIN32
#define stat _stat
#endif
//return true if the number of chars read is the same as the file size
bool IsDone() const
{
cout << "checking if numRead " << numRead << " is fileSize " << fileSize << endl;
return (numRead == fileSize);
}
char Read()
{
if (IsDone())
throw IllegalStateException("stream is done");
else
{
char c;
file.get(c);
cout << "reading: " << c << endl;
if (file.fail())
throw FileException(std::string("error reading from file ") + fileName);
++numRead;
return c;
}
}
void OpenFile(string fileName)
{
struct stat buf;
#ifdef WIN32
if (_stat(fileName.c_str(), &buf) < 0){
switch (errno){
case ENOENT:
throw FileException(std::string("Could not find file ") + name);
case EINVAL:
throw FileException(std::string("Invalid parameter to _stat.\n"));
default:
/* Should never be reached. */
throw FileException(std::string("Unexpected error in _stat.\n"));
}
}
#else
if (stat(fileName.c_str(), &buf) < 0)
throw FileException(std::string("could not determine size of file ") + fileName);
#endif
fileSize = buf.st_size;
file.open(fileName.c_str());
}
如果您想查看整个库,可以从here 获取。我知道代码看起来很粗糙;我只是想拼凑一个工作的Windows版本。这东西在 Linux 上运行良好;问题是,当我在 Windows 上读取文件时,我在输入文件中使用的每个换行符的大小都是 1 短,所以如果我有一个看起来像这样的文件:
text
它工作正常,但有:
text\r\n
它中断了,输出如下所示:
checking if numRead 0 is fileSize 6
checking if numRead 0 is fileSize 6
reading: t
checking if numRead 1 is fileSize 6
checking if numRead 1 is fileSize 6
reading: e
checking if numRead 2 is fileSize 6
checking if numRead 2 is fileSize 6
reading: x
checking if numRead 3 is fileSize 6
checking if numRead 3 is fileSize 6
reading: t
checking if numRead 4 is fileSize 6
checking if numRead 4 is fileSize 6
reading:
checking if numRead 5 is fileSize 6
checking if numRead 5 is fileSize 6
reading:
File Error: error reading from file H:/test/data/stuff.txt
它中断是因为 IsDone() 错误地返回 false(没有双关语),并且程序试图读取文件末尾。关于为什么 _stat 在有换行符时返回错误数字的任何建议?
【问题讨论】:
标签: c++ windows file mingw newline