using fstream to read every character including spaces and newline

前端 未结 13 1479
一个人的身影
一个人的身影 2020-12-07 22:47

I wanted to use fstream to read a txt file.

I am using inFile >> characterToConvert, but the problem is that this omits any spaces an

相关标签:
13条回答
  • 2020-12-07 23:29

    As Charles Bailey correctly pointed out, you don't need fstream's services just to read bytes. So forget this iostream silliness, use fopen/fread and be done with it. C stdio is part of C++, you know ;)

    0 讨论(0)
  • 2020-12-07 23:31

    Another better way is to use istreambuf_iterator, and the sample code is as below:

    ifstream inputFile("test.data");
    
    string fileData(istreambuf_iterator<char>(inputFile), istreambuf_iterator<char>());
    
    0 讨论(0)
  • 2020-12-07 23:32

    You can call int fstream::get(), which will read a single character from the stream. You can also use istream& fstream::read(char*, streamsize), which does the same operation as get(), just over multiple characters. The given links include examples of using each method.

    I also recommend reading and writing in binary mode. This allows ASCII control characters to be properly read from and written to files. Otherwise, an encrypt/decrypt operation pair might result in non-identical files. To do this, you open the filestream with the ios::binary flag. With a binary file, you want to use the read() method.

    0 讨论(0)
  • 2020-12-07 23:32
    ifstream ifile(path);
    std::string contents((std::istreambuf_iterator<char>(ifile)), std::istreambuf_iterator<char>());
    ifile.close();
    
    0 讨论(0)
  • 2020-12-07 23:36
    std::ifstream ifs( "filename.txt" );
    
    std::string str( ( std::istreambuf_iterator<char>( ifs ) ), 
                     std::istreambuf_iterator<char>()
                   );
    
    0 讨论(0)
  • 2020-12-07 23:39

    For encryption, you're better off opening your file in binary mode. Use something like this to put the bytes of a file into a vector:

    std::ifstream ifs("foobar.txt", std::ios::binary);
    
    ifs.seekg(0, std::ios::end);
    std::ifstream::pos_type filesize = ifs.tellg();
    ifs.seekg(0, std::ios::beg);
    
    std::vector<char> bytes(filesize);
    
    ifs.read(&bytes[0], filesize);
    

    Edit: fixed a subtle bug as per the comments.

    0 讨论(0)
提交回复
热议问题