更新:要解決以下問題,我已經做了`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)可能是相關的(不知道它是否是一個愚蠢的)。 –