简体   繁体   English

在file.get(char c)和file.get(char * c,int length)之间的区别

[英]difference betwen file.get(char c) and file.get(char *c, int length)

I am writting a function for my code. 我正在为我的代码编写一个函数。
the function only need a opened file to process. 该功能只需要一个打开的文件即可处理。

here the code of the function : 这里的功能代码:

void printFile(std::ifstream &file)
{
    file.seekg(0, file.end);
    int length = file.tellg();
    file.seekg(0, file.beg);

    char *buffer = new char[length];
    file.get(buffer, length);
    file.seekg(0, file.beg);
    char c;
    int i = 0;
    std::cout << "Uncreypted file" << std::endl;
    while (file.get(c))
    {   
        // loop getting single characters

        std::cout << c << " " << buffer[i] << " ";
        i++;
    }
    std::cout << std::endl;

    delete[] buffer;
}

the result is weird : 结果很奇怪:

Uncrypted file 未加密的文件
thhiissiissaatteesstt thhiissiissaatteesstt
t ═ h ═ i ═ s ═ ═ i ═ s ═ ═ a ═ ═ l ═ i ═ g ═ n ═ ═════════

after one line the buffer output something different where as file.get.(c) work proprely, why ? 在一行之后,缓冲区输出与file.get.(c)工作的地方不同的东西,为什么?
Is this because of the carriage return ascii letter ? 这是因为the carriage return ascii letter吗?

after one line the buffer output something different 一行后,缓冲区输出不同的东西

That's because you did not read the documentation for the functions that you've used. 这是因为您没有阅读所用功能的文档。

file.get(buffer, length) stops at the first newline by default ( ref ). 默认情况下file.get(buffer, length)在第一个换行处停止ref )。

So, your buffer only contains the first line of the file. 因此, buffer仅包含文件的第一行。
Your other buffer[i] accesses are pulling out nonsense. 您的其他buffer[i]访问正在废话。

Read about how best to read a whole file into a string in C++ . 阅读有关如何最好地在C ++中将整个文件读入字符串的信息

And don't program "blind", then act surprised when your program doesn't do what you wanted; 而且,不要编写“盲目”程序,然后在程序没有执行所需的操作时感到惊讶;
read the documentation ! 阅读文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM