I have two text files, which appear to be identical in a text editor, but my C++ code for reading the files produces different line-counts for each file. I can't figure out where the files are different, or how to accommodate such difference in my C++ code.
Let me explain...
I have two text files, d1.txt and d2.txt. Each contains 100 numbers, 1 per line. When I open either of the files in vim and enter :set list!
, there are only 100 lines, each containing a number and the end-of-line character ($) after the last number on each line. In other words, when looking at them in vim, they look identical, with the exception of different precision in the numbers. There is different precision because one file came from MATLAB and the other from Gnumeric.
A quick diff of the files renders the following output (I use braced elipses "[...]" to omit portions in the interest of space):
1,28c1,28
< 0.01218465532007
[...]
< 0.01327976337895
---
> 0.0121846553200678
[...]
> 0.0132797633789485
30,100c30,100
< 0.01329705254301
[...]
< 0.00017832496354
---
> 0.0132970525430057
[...]
> 0.000178324963543758
\ No newline at end of file
Despite the message about the absence of a newline at the end of the second file (d2.txt), I can't see any difference when examining the last lines of the files in vim, as I mentioned above.
I have created a C++ function readVectorFromFile(std::vector<double>&,const string)
that returns the number of lines read from the respective text file. When I read the text files using the code:
std::cout << "d1.txt has " << readVectorFromFile(v1,"./d1.txt") << " lines.\n";
std::cout << "d2.txt has " << readVectorFromFile(v1,"./d1.txt") << " lines.\n";
I get the output:
d1.txt has 99 lines.
d2.txt has 100 lines.
The function is defined in the following way:
int readVectorFromFile(vector<double>& vec, const string& fullFilePathName) {
int value, numLines;
char line[10000];
ifstream inFile;
/* attempt to open file */
inFile.open(fullFilePathName.c_str());
if (inFile.fail()) {
LOG(FATAL) << "Unable to open file \"" << fullFilePathName.c_str() << "\" for reading.";
} else {
cout << "Importing vector from file " << fullFilePathName.c_str() << "\n";
}
/* records the number of lines in the input file */
numLines = static_cast<int>( count(istreambuf_iterator<char>(inFile),
istreambuf_iterator<char>(), '\n') );
/* start file over from beginning */
inFile.clear();
inFile.seekg(0, ios::beg);
vec.clear(); // clear current vec contents
vec.reserve(numLines);
/* read value from each line of file into vector */
for(int i=0; i<numLines; ++i) {
inFile.getline(line, 10000);
vec.push_back( strtod(line,NULL) );
}
inFile.close(); // close filestream
return numLines; // return the number of lines (values) read
}
Why can I not see the difference between these files when I view them in vim? Is there anything fundamentally wrong with the above function that is causing this problem?