【发布时间】:2018-03-29 04:27:57
【问题描述】:
编辑:
我发现了我的错误。它与文本文件本身有关。我设法制作了两个不同大小的文本文件;并在比较大小时引用了错误的文件。
对于所有评论和回复,我确实考虑了所有反馈。谢谢!
在大学课堂上的实验室工作。我一直很难弄清楚如何阅读包含“爱丽丝梦游仙境”完整文本的 .txt 文件的全部内容。
一些上下文:
这只是构建 openCL 程序的起点,该程序将为字符串搜索执行 MapReduce(即计算“Alice”在文本中出现的次数)。该程序正在Ubuntu虚拟机上编译和运行;稍后为 FPGA 编译。
Ubuntu 告诉我文件大小为 148,545 字节。 我的代码是 53073 字节。当我尝试打印它时,它也不会读出整个文件。
从功能上讲,代码目前适用于文件的一部分(爱丽丝梦游仙境文本)。但它似乎并没有阅读/搜索整个文本。我一直在寻找解决我的困境的答案,但我一直没有成功。
所以! 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <fstream>
#include "CL/opencl.h"
#include "AOCL_Utils.h"
using namespace std;
int main(int argc, char** argv) {
string line;
long wordMatch, wordLength;
wchar_t* inputLine;
ifstream inputText;
inputText.open("alice.txt", ifstream::binary | ifstream::in); // Open the text
inputText.seekg(0, ios::end);
int length = inputText.tellg(); // Gives back the wrong byte size
cout << length << "\n";
inputText.close();
char * textBuffer = new char [length];
wordMatch = 0;
inputText.open("alice.txt"); // Could've just seeked to the start
inputText.read(textBuffer, inputText.gcount());
//cout << inputText.gcount() << " bytes in file \n"; // Trying to get correct bytesize
while(getline(inputText,line)) // Read out the text, but stops before it's finished
{
cout << line << "\n";
}
inputLine = (wchar_t*) "Alice"; // What we're counting occurrences of
// My little counting routine. Works fine.
for (int i = 0; i < length; i++)
{
if (textBuffer[i] == inputLine[0])
{
wordLength = 0;
if (textBuffer[i] == inputLine[0]) {
while (textBuffer[i+wordLength] == inputLine[wordLength]) {
//cout << textBuffer[i+wordLength] << " and " << inputLine[wordLength] << "\n";
wordLength++;
}
if (inputLine[wordLength] == 0) {
wordMatch++;
}
}
}
}
inputText.close();
cout << length << " bytes \n";
cout << wordMatch << "\n";
return 0;
}
【问题讨论】:
-
您的代码中存在内存泄漏。一旦你不需要它,你应该释放
textBuffer -
为什么是
(wchar_t*) "Alice"?textBuffer[i] == inputLine[0]很少是真的(而且你要检查两次)。 -
为什么你有
ifstream::binary | ifstream::in使用或者|应该用于in和out模式而不是binary和in,因为它们都是写作模式。跨度>