c++ - (C++) noob - 我的代码有什么问题?

标签 c++ ifstream

<分区>

我正在尝试读取给定文件中的字符并输出十六进制字符的数量。当我对一个文本文件运行它时,它或多或少是准确的,但对于其他任何东西,它似乎都不太准确。 IE:大约 700MB 的 *.mp4 文件将以 12K 显示。我在这里错过了什么?

#include <fstream>
#include <iostream>
using namespace std ;

int main()
    {
    char letter ;
    int i ;
    cout << "Input the filename:" << endl;
    string stringinput;
        cin >> stringinput;
    ifstream file( stringinput.c_str() ) ;
    if( ! file )
    {
        cout << "Error opening input file, " << ( stringinput ) << ". Check file path and try again." << endl ;
        return -1 ;
    }
    else
        for( i = 0; ! file.eof() ; i++ )
        {
            file.get( letter ) ;
            //cout << hex << (int) letter;
        }
        cout << endl;
        float k = 1024, m = 1048576;
        file.close();
        if( i < 1024)
        {
            cout << "Total: " << dec << i << endl;
        }
        else if( i < m)
        {
            cout << "Total: " << dec << (i / k) << "K" << endl;
        }
        else
        {
            cout << "Total: " << dec << (i / m) << "M" << endl;
        }
        return 0 ;
}

最佳答案

您需要以binary 模式打开文件。

ifstream file( stringinput.c_str() ) ;

应该是:

ifstream file( stringinput.c_str(), ios_base::in | ios_base::binary ) ;

以文本模式读取文件意味着某些字符(例如 CTRL-Z)被视为“文件结尾”,因此如果这恰好是您输入的一部分,您的读取将提前结束。由于 mp4 文件是具有相当“随机”内容的二进制文件,因此不能保证这些字符不会出现在文件中。

关于c++ - (C++) noob - 我的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725284/

相关文章:

c++ - 无法在头文件中声明 ifstream 类成员

C++ getline() 在 clear() 之后

c++ - 为什么使用 conio.h?

C++ 中的 Java 接口(interface)

c++ - 在 C 或 C++ 中为多个输入执行 while 循环

c++ - 如何使用 STL C++ 读取文件和保存连字符

C++ 从 *.txt 文件读取数据到结构 vector

c++ - QML:QQmlListProperty<T>。 T 必须是 QObject 吗?

C++ If 语句,从 else 开始重复

C++ ifstream 到 char *