C ++以二进制模式读取文件.文件结尾问题 [英] C++ reading a file in binary mode. Problems with END OF FILE

查看:70
本文介绍了C ++以二进制模式读取文件.文件结尾问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,我必须以二进制模式读取文件.这是我的操作方法(遵循C ++参考):

I am learning C++and I have to read a file in binary mode. Here's how I do it (following the C++ reference):

unsigned values[255];
unsigned total;
ifstream in ("test.txt", ifstream::binary);

while(in.good()){
    unsigned val = in.get();
    if(in.good()){
        values[val]++;
        total++;
        cout << val <<endl;
    }
}

in.close();

因此,我正在逐字节读取文件字节,直到 in.good()为真.我在 while 的末尾放了一些 cout ,以了解发生了什么,这是输出:

So, I am reading the file byte per byte till in.good() is true. I put some cout at the end of the while in order to understand what's happening, and here is the output:

marco@iceland:~/workspace/huffman$ ./main 
97
97
97
97
10
98
98
10
99
99
99
99
10
100
100
10
101
101
10
221497852
marco@iceland:~/workspace/huffman$

现在,输入文件"test.txt"就是:

Now, the input file "test.txt" is just:

aaaa
bb
cccc
dd
ee

所以一切正常,直到结束为止,那里是221497852.我想这与文件结尾有关,但是我无法找出问题所在.

So everything works perfectly till the end, where there's that 221497852. I guess it's something about the end of file, but I can't figure the problem out.

我正在使用gedit&在Debian机器(64位)上使用g ++.任何帮助将不胜感激.

I am using gedit & g++ on a debian machine(64bit). Any help help will be appreciated.

非常感谢,

马可

推荐答案

我终于弄清楚了.显然,问题并非出自任何代码.问题是gedit.它总是在文件末尾附加一个换行符.其他编辑器(例如vim)也会发生这种情况.对于某些编辑器,可以将其配置为不附加任何内容,但是在gedit中,这显然是不可能的. https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-of-file-newline-char

I've eventually figured this out. Apparently it seems the problem wasn't due to any code. The problem was gedit. It always appends a newline character at the end of file. This also happen with other editors, such as vim. For some editor this can be configured to not append anything, but in gedit this is apparently not possible. https://askubuntu.com/questions/13317/how-to-stop-gedit-gvim-vim-nano-from-adding-end-of-file-newline-char

为所有问我的人欢呼

马可

这篇关于C ++以二进制模式读取文件.文件结尾问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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