如何从文件的结尾读取第6个字符 - ifstream? [英] How to read the 6th character from the end of the file - ifstream?

查看:563
本文介绍了如何从文件的结尾读取第6个字符 - ifstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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";
    }
}

档案包含:

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

该函数返回的值是 5 ,而第六个字符结束 0

我在哪里出错?

The value returned by that function is 5, whereas the sixth character from the end is 0!
Where am I going wrong?

推荐答案

在文本文件中寻找任意位置是未定义的行为。
在实践中,它可能在各种Unices下工作,但没有在
else。如果以二进制模式打开文件,则搜索是合法的。
正式来说,如果以二进制模式打开文件,最后可能会得到额外的nul
字节,但实际上,这不是今天的问题。如果
以二进制模式打开,您可能会在数据中看到别的东西,而不是
'\\\
'
例如,在Windows下,您将看到两个
字符序列 0x0D,0x0A

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.

最后,显示的数据中从第六个字符开始的是
'2',而不是'0'。但是当然,在
Unix之外的系统上,你可以很容易看到别的东西(或得到一个错误):可能是
'。' Windows或在某些大型机操作系统下的错误(或可能是一个''')。

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.

这篇关于如何从文件的结尾读取第6个字符 - ifstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆