我正在编写一个程序,它的第一步是从大约 30MB 的文本文件中读取。这些文件是 0 到 255 之间的一系列数字,偶尔会有换行符(ImageJ 文本图像,通过 RGB 堆栈)。vector<int>
我可以毫无问题地将数据读入 a ,并vector<vector<int> >
为 RGB 部分形成 a 。但是,我想知道我的图像的高度和宽度。
总数可通过 获得myVector[0,1,2].size()
,但除非我也知道纵横比,否则我无法从中获得高度/宽度。
如果我使用file.get(nextChar); if (nextChar == '\n'){...}
,那么代码将继续阅读,afaik。
我尝试单独读取一行中的字符而不是读取文件,但是除了增加运行时间(这不是什么大问题)之外,我还有一个更严重的问题,因为文件包含tab
空格,而不是真正的空格,因此,虽然我最初认为每个数字是 4 个字符,例如123(space)
or12(space)(space)
等,但事实证明它们是123(tab)
and 12(tab)
,它们具有不同的字符数。
我如何计算每行的字数?示例代码如下:
void imageStack::readFile(const char *file, std::vector<int> &values)
{
std::ifstream filestream;
filestream.open(file);
if (!filestream.fail())
{
std::cout<< "File opened successfully: " << file << std::endl;
int countW=0;
char next;
while (!filestream.eof())
{
int currentValue;
filestream >> currentValue;
values.push_back(currentValue);
countW++;
if (filestream.get(next)=='\n')
// This doesn't work, but I think if I used filestream.get(next);
// if (next == '\n') that would check correctly,
// it would just move the file marker
{
std::cout<< "countW = " << countW << std::endl;
}
}
filestream.close();
values.pop_back();
}
else
{
std::cout << "File did not open! Filename was " << file << std::endl;
}
}
下面的代码计算不准确:
std::vector<int> imageStack::getDimensions(const std::string fileName)
{
std::vector<int> dim(2);
std::stringstream rfN;
rfN << fileName << "R";
std::string rFileName = rfN.str();
const char *file_ptr;
file_ptr = rFileName.c_str();
std::ifstream file;
file.open(file_ptr);
int widthCount=-1, heightCount=-1;
if (!file.fail())
{
char next;
int counterW = 0;
int counterH = 0;
while(file.get(next))
{
counterW++;
if (next == '\n')
{
counterH++;
if (widthCount == -1)
{
std::cout << "The first line has " << counterW << " characters." << std::endl;
}
if (widthCount != -1 && widthCount != counterW)
{
//~ std::cout<< "The width counter didn't get the same number every time!" << std::endl;
//~ std::cout<< "widthCount = " << widthCount << std::endl;
//~ std::cout<< "counterW = " << counterW << std::endl;
}
widthCount = counterW;
counterW = 0;
}
heightCount = counterH;
}
file.close();
}
//~ std::cout << "Values found for width and height are "
//~ << widthCount << ", " << heightCount << std::endl;
dim[0] = ((widthCount-1)/4);
dim[1] = heightCount;
return dim;
}