This is my first post. I have a c++ program and a c program. The c program produces data to standard out that the c++ program should read. The data can contain the character '\0'. The data are stored in char*. I have to refactor the code because right now it is using strcat, strlen and printf("%s", char_array).
1. How can I write char* to stdout in the c program? (without c++). Is looping through char* efficient? Is printf ok? I seem to be unable to use std::cout.
2. In the c++ program I use fgets to read the data. fgets writes to a char array. I think I should move it to a string a.s.a.p. Is there an efficient way to do this?
In most cases the data is html and I want to perform string operations on that in the c++ program, which is why I want to move it to a string. Sometimes the data is gzipped, which is why it may contain null characters.
Thanks for the info about std::cout. I think what you say about printf and new string is wrong. Those can't handle null characters in the char array. That was the whole problem.
It seems to be possible to work it around by looping through the char array. This won't work for one of the functions I am using though: popen. I think popen cannot pass binary data in the command, because the command is a char array and that char array may contain null chars (as in my case). Does anyone have a solution?
edit: I found that I need to read from and write to popen, which is impossible. PStreams is probably going to save me: http://pstreams.sourceforge.net/
" I think what you say about printf and new string is wrong. Those can't handle null characters in the char array."
If you're interpreting the array of chars as a c-sytle string, the null character defines the end of the array. It is not in the array - it is the end of the array.
The popen() function only creates another process, and no process has a null character in its name. Once you have the process open, you can read and write to its standard streams as usual.
To write or read a character array containing nulls to a stream, use one of the unformatted I/O functions, like fwrite() and fread() (working with FILE*) or write() and read() (working with a file descriptor). All of these functions allow you to specify how many bytes (characters) to process.
Moschops, that's the whole point. My char arrays contain null characters (because it's contained in the data). Therefore, my char arrays are NOT c-style strings, so I can't use those c-string functions.
Duoas, thanks for your reply. As far as I can find out, you can't read AND write to the popen standard streams (I tried, if you know how, please let me know). You can do either but not both (unless with forking).
I mentioned PStreams. They claim it's possible to read and write, but I didn't find out how so far.