Page 1 of 1

platform independent c++ string length

Posted: Fri Dec 13, 2019 8:13 am
by ksharindam
I am creating a cross platform program which has a pdf writer.
I am writing string like this,

Code: Select all

    std::string header;
    header = "%PDF-1.4\n";
    int offset = header.size();
    
    std::ofstream stream;
    stream.open(filename);
    stream << header;
    stream.close();
in both linux and windows, the returned offset is 9. In linux number of actual written bytes is 9, but in windows it is 10.
This may be due to the different line ending types. linux uses LF and windows uses CRLF (\r\n).

How can I get the actual size of the string that is written?
Or how can I use only LF newline even in windows platform?

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 8:33 am
by scotty101
Seems more like a question for stack overflow than a Raspberry Pi forum.

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 8:53 am
by LdB
tellp
http://www.cplusplus.com/reference/ostr ... eam/tellp/
In your case read the value stream.tellp();

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 11:35 am
by njh
It's not the question you asked, but: To write the identical PDF file on any platform (including a Pi) you should open a new file in binary mode and write the bytes required. Otherwise you will run into trouble when you write the "xref" section, or if you need any compressed or binary objects.

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 11:50 am
by ksharindam
LdB wrote:
Fri Dec 13, 2019 8:53 am
tellp
http://www.cplusplus.com/reference/ostr ... eam/tellp/
In your case read the value stream.tellp();
Tried it, but it returns 9 in both windows and linux.

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 12:16 pm
by topguy
But you are saying that the file-size on Windows is 10 bytes ?

( I also think Njh had the best idea )

Re: platform independent c++ string length

Posted: Fri Dec 13, 2019 12:21 pm
by ksharindam
njh wrote:
Fri Dec 13, 2019 11:35 am
It's not the question you asked, but: To write the identical PDF file on any platform (including a Pi) you should open a new file in binary mode and write the bytes required. Otherwise you will run into trouble when you write the "xref" section, or if you need any compressed or binary objects.
Thanks. It works.
I opened the file in binary mode using...

Code: Select all

stream.open(filename, std::ios::out|std::ios::binary);