void maintainFileName ()
{
std :: ifstream myfile;
myfile.open ("zoomLevels.txt");
if (myfile.is_open ())
{
// Move to end of the file,
myfile.seekg (0, std::ios::end);
// and then six characters back to pick up the last file number.
myfile.seekg (6, std::ios::beg);
int len = 1;
char *t = new char[len];
myfile.read(t, len);
qDebug () << "\nt: " << *t << "\n";
}
else
{
qDebug () << "\nsorry";
}
}
The file contains this:
78.8115,29.582,1,01.rda
78.8115,29.582,2,02.rda
76.3671,30.2201,1,11.rda
76.3671,30.2201,2,12.rda
78.1908,30.3007,1,01.rda
78.1908,30.3007,2,02.rda
77.3284,29.1415,1,01.rda
77.3284,29.1415,2,02.rda
77.3064,29.1655,1,01.rda
77.3064,29.1655,2,02.rda
The value returned by that function is 5
, whereas the sixth character from the end is 0
!
Where am I going wrong?
Seeking to an arbitrary position in a text file is undefined behavior.
In practice, it will probably work under various Unices, but no where
else. If you open the file in binary mode, the seek is legal.
Formally, if you open the file in binary mode, you may get extra nul
bytes at the end, but in practice, this isn't a problem today. If you
open it in binary mode, however, you may see something else instead of
'\n'
in the data; under Windows, for example, you'll see the two
character sequence 0x0D, 0x0A
.
Of course, in your code, you're seeking from the beginning, not from the end. This is also undefined behavior, but most of the time, it will work as long as you are seeking in the first line.
And finally, the sixth character from the end in the data you show is a
'2'
, not a '0'
, as you write. But of course, on systems other than
Unix, you could easily see something else (or get an error): probably a
'.'
under Windows, or or an error (or maybe a '' '
) under some mainframe OS.