4

I am using the C++ streams to read in a bunch of files in a directory and then write them to another directory. Since these files may be of different types, I am using a the generic ios::binary flag when reading/writing these files. Example code below:

std::fstream inf( "ex.txt", std::ios::in | std::ios::binary);
char c;
while( inf >> c ) {
    // writing to another file in binary format
}

The issue I have is that in the case of files containing text, the end of line characters in these text files are not being written to the output file.

Edit: Or at least they do not appear to be as when the newly written file is opened, there is only a single continuous line of characters.

Edit again: The problem (of the continuous string) appears to persist even when the read / write is made in text mode.

Thus, I was wondering if there was a way to check if a file has text or binary and then read/write it appropriately. Else, is there any way to preserve the end of line characters even when opening the file in binary format?

Edit: I am using the g++ 4.8.2 compiler

nave
  • 428
  • 5
  • 19
  • 4
    The *newlines* aren't being transferred? Are you sure? I'm pretty certain that would be a serious deviation from the standard. Binary mode should copy everything exactly as is, including whatever encoding of newline exists in the file, `LF/CRLF/LFCR/etc`. – paxdiablo Nov 02 '15 at 08:12
  • What compiler are you using? – Paolo M Nov 02 '15 at 08:14
  • Added more information above – nave Nov 02 '15 at 08:19
  • If you just want to copy files between directories, you can always just do [`dest << src.rdbuf();`](https://stackoverflow.com/a/9125390/865719). (ps: remember to [`src.clear(); src.seekg(0);`](https://stackoverflow.com/a/28331018/865719) before doing that) – maddouri Nov 02 '15 at 08:36
  • Got the same behaviour in both reading modes (gcc 4.9.3) As a workaround, `istream::get()` method can be used (Just checked that). I don't exactly understand why but it seems that , when `>>` is used, the program tries to read formatted input, and that's indeed the case for *text mode* but I don't know why it's actually the case for binary mode. – DimG Nov 02 '15 at 09:04
  • DimG, could you post your code with the get() method? – nave Nov 02 '15 at 09:41
  • @nave `std::ifstream in( "ex.txt", std::ios_base::binary); std::ofstream out( "ex.txt.out", std::ios_base::binary); char c; while( True ) { c = in.get(); if (in.eof()) { break; } out << c;}`. – DimG Nov 02 '15 at 10:16
  • P.S. If you want the message reciever to be notified about comment, that type @ (at) sign before its name. – DimG Nov 02 '15 at 10:18

1 Answers1

2

When you want to manipulate bytes, you need to use read and write methods, not >> << operators.

You can get the intended behavior with inp.flags(inp.flags() & ~std::ios_base::skipws);, though.

vehsakul
  • 1,118
  • 1
  • 10
  • 17