更新:要解决以下问题,我已经做了`fgetpos`不返回正确的位置
if (ftell(m_pFile) != m_strLine.size())
fseek(m_pFile, m_strLine.size(), SEEK_SET);
fpos_t position;
fgetpos(m_pFile, &position);
这则返回我的文件的正确位置。但是,我仍然想明白为什么会发生这种情况?
我想获得文本文件中的位置。对于大多数的文件,我一直在读的第一线,存储位置,做一些其他的东西,回归后的位置...
m_pFile = Utils::OpenFile(m_strBaseDir + "\\" + Source + "\\" + m_strFile, "r");
m_strLine = Utils::ReadLine(m_pFile);
bEOF = feof(m_pFile) != 0;
if (bEOF)
{
Utils::CompilerError(m_ErrorCallback,
(boost::format("File '%1%' is empty.") % m_strFile).str());
return false;
}
// Open.
pFileCode = Utils::OpenFile(strGenCode + "\\" + m_strFile, options.c_str());
m_strLine = Utils::Trim(m_strLine);
Utils::WriteLine(pFileCode, m_strLine);
// Store location and start passes.
unsigned int nLineCount = 1;
fpos_t position;
fgetpos(m_pFile, &position);
m_strLine = Utils::ReadLine(m_pFile);
...
fsetpos(m_pFile, &position);
m_strLine = Utils::ReadLine(m_pFile);
随着我提供正确fgetpos
和fsetpos
作品的存储所有文件。问题是,我已经创建了一个文件,它看起来像
这几乎等同于提供的文件。问题是对于fgetpos(m_pFile, &position);
以上的文件没有返回正确的position
(我知道fpos_t position
是特定于实现的)。第一ReadLine
后,我得到一个position
58(编辑),所以,当我试图与
fsetpos(m_pFile, &position);
m_strLine = Utils::ReadLine(m_pFile);
读第二行,我得到
在700
而不是
选择函数ADJEXCL
为什么fgetpos
不返回第一行结尾的位置?
_注意。该Utils.ReadLine
方法是:
std::string Utils::ReadLine(FILE* file)
{
if (file == NULL)
return NULL;
char buffer[MAX_READLINE];
if (fgets(buffer, MAX_READLINE, file) != NULL)
{
if (buffer != NULL)
{
std::string str(buffer);
Utils::TrimNewLineChar(str);
return str;
}
}
std::string str(buffer);
str.clear();
return str;
}
与
void Utils::TrimNewLineChar(std::string& s)
{
if (!s.empty() && s[s.length() - 1] == '\n')
s.erase(s.length() - 1);
}
编辑。继在评论中调试建议我加入以下代码
m_pFile = Utils::OpenFile(m_strBaseDir + "\\" + Source + "\\" + m_strFile, "r");
m_strLine = Utils::ReadLine(m_pFile);
// Here m-strLine = " Logic Definition Report Chart Version: New Version 700" (64 chars).
long vv = ftell(m_pFile); // Here vv = 58!?
fpos_t pos;
vv = ftell(m_pFile);
fgetpos(m_pFile, &pos); // pos = 58.
fsetpos(m_pFile, &pos);
m_strLine = Utils::ReadLine(m_pFile);
我认为在“我创建的文件看上去像”和“几乎相同”之间有一点缺失。也就是说,在Windows上,当你在文本模式下阅读时,你需要小心换行符,这可能是你的问题。 – molbdnilo
谢谢你,我编辑了这个问题。该文本文件是用C#创建的,并使用默认编码('Encoding.Default')来编写文本文件。使用的行结尾是'\ r \ n',并且对于可以工作的文件似乎显示完全相同。我失去了为什么这个(我创建的文件)是40个中唯一一个无法使用上面的代码返回正确位置的!回报和换行符看起来不错!? – MoonKnight
[这个问题](http://stackoverflow.com/q/15649089/2065121)可能是相关的(不知道它是否是一个愚蠢的)。 –