stringstream - read a text file to stringstreem but keep line feed /CRLF

Hi,

I build this function in my C++ code. I run the on a UNIX box, build HTML file to use in Windows.

In HTML file building code, I have only a string variable hold the contents of this text file (from unix) & add it into HTML file.

The issue is that when I view the HTML file on windows, it shows all the lines in the text file as one line. I think it lost the CRLF.

My question is when I add lines from text file (reading one line at a time) in UNIX, how do I maintain CRLF (\r\n) in the stringstream variable so that it will display on HTML in Windows properly, all the lines as it is in unix.

Any help to improve/fix the below code will be much appreciated.

I am aware UNIX uses \n for line end.

1
2
3
4
5
6
7
8
9
10
11
12
string TextFileToString(string filename)
{
   string line;
   stringstream dosString;
   ifstream inFile;
   inFile.open (filename.c_str());
       while(getline(inFile, line))
        {           
           dosString<<line<<"\r\n";
        }
    return(dosString.str());
}


Mathew
Last edited on
After the text file (say myfile.txt) is created (on Unix),
> awk 'sub("$", "\r")' myfile.txt > myfile_on_windows.txt

Or transfer the file to the Windows box via FTP using text mode ('ASCII mode').

Hi Borges,

Thanks for the reply.

Well, I am trying to do it in C++ code, not on unix commands.

Any more help?

Mathew
1
2
3
4
5
6
7
8
9
10
std::string TextFileToString( std::string filename )
{
   std::ostringstream dosString( std::ios::out | std::ios::binary ) ; // *** binary
   std::ifstream inFile( filename.c_str() ) ;

   std::string line;
   while( std::getline(inFile, line) ) dosString << line << "\r\n" ;

    return dosString.str() ;
}
Hi Borges,

Thanks for the above - new one learnt.
That seems to work so far and if any issues, I will post here.

Mathew
Topic archived. No new replies allowed.