ifstream正在复制文件中的数据

时间:2013-05-30 16:16:06

标签: duplicates ifstream

所以我对此感到有些困惑,我无法确切知道我的文件输入到底发生了什么。我应该指出,我只是将其移植到Windows,这确实在Mac OS X上正常运行并且正如预期的那样。

基本上,我的问题是我的ifstream在读取时似乎是复制输入文件的尾部两次。例如,如果我的输入是:

Daisy, Daisy, give me your answer, do,
I'm half crazy all for the love of you.
It won't be a stylish marriage,
I can't afford a carriage,
But you'd look sweet upon the seat
Of a bicycle built for two. 

ifstream将按如下方式读入:

Daisy, Daisy, give me your answer, do,
I'm half crazy all for the love of you.
It won't be a stylish marriage,
I can't afford a carriage,
But you'd look sweet upon the seat
Of a bicycle built for two. 
I can't afford a carriage,
But you'd look sweet upon the seat
Of a bicycle built for two. 

这是有问题的代码:

std::ifstream initialResults(inputFileLocation.toStdString().c_str());
std::string fileInMemory;
initialResults.seekg(0,initialResults.end);
fileInMemory.resize(initialResults.tellg());
initialResults.seekg(0,initialResults.beg);
initialResults.read(&fileInMemory[0],fileInMemory.size());
initialResults.close
//Printing here, the file in memory already contains the duplicate entries
std::cout << fileInMemory << "\n";

我根本不确定导致此行为的原因。我不太熟悉在Windows上开发与Mac相反,并且考虑到程序是相同的,但产生了这些不同的结果,我将走出困境并说这是Window特有的。也许函数的差异叫做结束和乞讨?但我无法想象为什么它会重新复制文件的尾部。是的,我已检查过该文件,并且其中没有重复的条目。

1 个答案:

答案 0 :(得分:0)

经过进一步研究,我很确定这是Windows中回车/换行问题。您需要以二进制模式ios_base::binary打开文件以禁止转换。