C++ fwrite() in hex - c++

Writing code with Winsock.
I currently have this:
fwrite(buff, 1, len, stdout);
How to do it like:
for ( int i = 0; i < len; i++ ) {
printf( "%02x ", unsigned char (buff[i]) );
}
printf( "\n" );
Or should I just remove the fwrite and use the print instead?
I wanted to write it to stdout, cuz I have my option to either write to stdout of write to file.

fprintf (see the docs) is like printf but to an arbitrary file:
fprintf(stdout, "%02x ", unsigned char (buff[i]));

Related

different results with printf and fprintf

I need function that prints "word=n" (where n in [0..10]) to stream using linux function ssize_t write(int fd, const void *buf, size_t count);. Trying to use fprintf, but it's give strange results : program prints in ~1% of calls "woword=n", and length for example "woword=7" are 7. Printf print all right. I'm doing something wrong or this is the bag ?
if ((id_result = open( out , O_WRONLY)) <= 0) {
fprintf(stderr, "%s : %s\n", currentDateTime().c_str(), "could not open output\0");
ret = P_STREAMS_LOAD_ERROR;
}
void printProbability( int probability ){
char buf[50];
memset( buf, '\0', 50 );
int length = sprintf( buf, "word=%i\n\0", probability );
fprintf(stderr, "debug : word=%i len = %i\n\0", probability, length );
int result = write( id_result, buf, length );
if( result == -1){
fprintf(stderr, "%s : %s\n", currentDateTime().c_str(), "error \n");
}
}
EDITED:
how I understand, we have 2 theorys :
1) mixing printf and write
2) using '\0' and '\n' in fprintf
int length = sprintf( buf, "word=%i", probability );
int result = write( id_result, buf, length );
write( id_result, "\n", 1 );
with this code I still have same errors
aa help me :))
If you are interspersing calls to printf (or write) and fprintf(stderr, ...) the output won't necessarily come out in order. There is buffering going on, and the actual output probably won't switch at the end-of-line character.

Pointer Arithmetic, Pass by Reference

I got the following question from a past exam paper:
Consider the following source code:
using namespace std;
int main()
{
char dest[20];
printf( "%s\n", altcopy( dest, "demo" ) );
printf( "%s\n", altcopy( dest, "demo2" ) );
printf( "%s\n", altcopy( dest, "longer" ) );
printf( "%s\n", altcopy( dest, "even longer" ) );
printf( "%s\n", altcopy( dest, "and a really long string" ) );
}
Provide an implementation for the function called altcopy() which uses pointer arithmetic to copy alternate characters of a C-type string to the destination (i.e. the first, third, fifth etc character). Your answer must not use the [] operator to access an array index. The above code would then output the following:
dm
dm2
lne
ee ogr
adaral ogsrn
And I have attempted as follows:
using namespace std;
char* altcopy (char* dest, const char* str)
{
char* p = dest;
const char* q = str;
for ( int n=0; n<=20; n++ )
{
*p = *q;
p++;
q++;
q++;
}
return dest;
}
int main()
{
char dest[20];
printf( "%s\n", altcopy( dest, "demo" ) );
printf( "%s\n", altcopy( dest, "demo2" ) );
printf( "%s\n", altcopy( dest, "longer" ) );
printf( "%s\n", altcopy( dest, "even longer" ) );
printf( "%s\n", altcopy( dest, "and a really long string" ) );
}
And the results are:
dm
dm2lne
lne
ee ogradaral ogsrn
adaral ogsrn
I'm not sure why it happened to have duplicate of next statement result on certain output instead of performing as what the question asked for. Any help here?
Your function is invalid at least because it uses magic number 20.
The function should be similar to standard function strcpy That is it has to copy the source string until the terminating zero will be encountered.
Here is a simple function realization
#include <iostream>
char * altcopy( char *dest, const char *str )
{
char *p = dest;
while ( *p++ = *str++ )
{
if ( *str ) ++str;
}
return dest;
}
int main()
{
char dest[20];
std::cout << altcopy( dest, "demo" ) << std::endl;
std::cout << altcopy( dest, "demo2" ) << std::endl;
std::cout << altcopy( dest, "longer" ) << std::endl;
std::cout << altcopy( dest, "even longer" ) << std::endl;
std::cout << altcopy( dest, "and a really long string" ) << std::endl;
return 0;
}
The output is
dm
dm2
lne
ee ogr
adaral ogsrn
Enjoy!:)
Since in your loop:
for ( int n=0; n<=20; n++ )
{
*p = *q;
p++;
q++;
q++;
}
you are just looping 20 times regardless of the string length you are reading random memory from past the end of the string. In most cases you probably read a 0 after the real characters and write that next which terminates the string as far as printf is concerned, but sometimes because the way the strings happen to be stored in memory you are getting some characters from the next string.
It's because q++ is being done twice, and it skips over the terminating null, and into the next string.
In fact it doesn't even check for the terminating null.

using fwrite() & fread() for binary in/output

I'm using a large array of floats. After a lot of fiddling I've managed to write it to a binary file. When opening that file at a later time, the reading process only reads a couple of handfuls of floats (according to the return-value of fread(), and it's all values 0.0f). The reading is supposed to put the floats into an (the original) array, and it does not contain the original values.
I'm using Code::Blocks and MinGW doing a program in the 32bit realm on a 64bit pc .. and I'm not very proficient on c/c++ and pointers.
#include<...>
const int mSIZE = 6000 ;
static float data[mSIZE*mSIZE] ;
void myUseFunc(){
const char *chN = "J:/path/flt_632_55.bin" ;
FILE *outFile=NULL ;
# .. sucessfully filling and using data[]
..
size_t st = mSIZE*mSIZE ;
outFile = fopen( chN , "w" ) ;
if(!outFile){ printf("error opening file %s \n", chN); exit(0);}
else{
size_t indt;
indt = fwrite( data , sizeof(float), st , outFile );
std::cout << "floats written to file: " << indt << std::endl ;
#.. value shows that all values ar written
# and a properly sized file has appeared at the proper place
}
fclose( outFile ) ;
}
void myLoadFunc( const char *fileName){
FILE *inFile = NULL ;
inFile = fopen( fileName, "r");
if(!inFile){ printf("error opening file %s \n", fileName); exit(0); }
size_t blok = mSIZE*mSIZE ;
size_t out;
out = fread( dataOne, sizeof(GLfloat), blok , inFile);
fclose(inFile);
if(out != blok){
std::cout<< out << std::endl ;
fputs ("Reading error",stderr);
# no stderr presented at the console ..
printf("some error\n") ;
exit(0);
# .. program exits at out=14
}
...
}
int main( ){
...
const char *FileName = "J:/path/flt_632_55.bin" ;
myLoadFunc( FileName ) ;
...
}
You are not writing to/reading from a binary file, you open the files as text files.
You need to add the "b" to the open mode, like
outFile = fopen( chN , "wb" ) ;

Unicode File Writing and Reading in C++?

Can anyone Provide a Simple Example to Read and Write in the Unicode File a Unicode Character ?
try http://utfcpp.sourceforge.net/. the link has an introductory example to read a utf8 file, line by line.
On linux I use the iconv (link) library which is very standard. An overly simple program is:
#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>
#define BUF_SZ 1024
int main( int argc, char* argv[] )
{
char bin[BUF_SZ];
char bout[BUF_SZ];
char* inp;
char* outp;
ssize_t bytes_in;
size_t bytes_out;
size_t conv_res;
if( argc != 3 )
{
fprintf( stderr, "usage: convert from to\n" );
return 1;
}
iconv_t conv = iconv_open( argv[2], argv[1] );
if( conv == (iconv_t)(-1) )
{
fprintf( stderr, "Cannot conver from %s to %s\n", argv[1], argv[2] );
return 1;
}
bytes_in = read( 0, bin, BUF_SZ );
{
bytes_out = BUF_SZ;
inp = bin;
outp = bout;
conv_res = iconv( conv, &inp, &bytes_in, &outp, &bytes_out );
if( conv_res >= 0 )
{
write( 1, bout, (size_t)(BUF_SZ) - bytes_out );
}
}
iconv_close( conv );
return 0;
}
This is overly simple to demonstrate the conversion. In the real world you would normally have two nested loops:
One reading input, so handle when its more than BUF_SZ
One converting input to output. Remember if you're converting from ascii to UTF-32LE you will end up with each iunput byte being 4 bytes of output. So the inner loop would handle this by examining conv_res and then checking errno.
In case you're using Windows.
Use fgetws http://msdn.microsoft.com/en-us/library/c37dh6kf(VS.71).aspx to read
and fputws http://msdn.microsoft.com/en-us/library/t33ya8ky(VS.71).aspx to write.
The example code are in the provided links.

How can I read keyboard input to character strings? (C++)

getc (stdin) reads keyboard input to integers, but what if I want to read keyboard input to character strings?
#include "stdafx.h"
#include "string.h"
#include "stdio.h"
void CharReadWrite(FILE *fin);
FILE *fptr2;
int _tmain(int argc, _TCHAR* argv[])
{
char alpha= getc(stdin);
char filename=alpha;
if (fopen_s( &fptr2, filename, "r" ) != 0 )
printf( "File stream %s was not opened\n", filename );
else
printf( "The file %s was opened\n", filename );
CharReadWrite(fptr2);
fclose(fptr2);
return 0;
}
void CharReadWrite(FILE *fin){
int c;
while ((c=fgetc(fin)) !=EOF) {
putchar(c);}
}
Continuing with the theme of getc you can use fgets to read a line of input into a character buffer.
E.g.
char buffer[1024];
char *line = fgets(buffer, sizeof(buffer), stdin);
if( !line ) {
if( feof(stdin) ) {
printf("end of file\n");
} else if( ferror(stdin) ) {
printf("An error occurerd\n");
exit(0);
}
} else {
printf("You entered: %s", line);
}
Note that ryansstack's answer is a much better, easier and safer solution given you are using C++.
http://www.cplusplus.com/reference/iostream/istream/getline/
Ta da!
A character (ASCII) is just an unsigned 8 bit integral value, ie. it can have a value between 0-255. If you have a look at an ASCII table you can see how the integer values map to characters. But in general you can just jump between the types, ie:
int chInt = getc(stdin);
char ch = chInt;
// more simple
char ch = getc(stdin);
// to be explicit
char ch = static_cast<char>(getc(stdin));
Edit: If you are set on using getc to read in the file name, you could do the following:
char buf[255];
int c;
int i=0;
while (1)
{
c = getc(stdin);
if ( c=='\n' || c==EOF )
break;
buf[i++] = c;
}
buf[i] = 0;
This is a pretty low level way of reading character inputs, the other responses give higher level/safer methods, but again if you're set on getc...
Since you already are mixing "C" code with "C++" by using printf, why not continue and use scanf scanf("%s", &mystring); in order to read and format it all nicely ?
Or of course what already was said.. getline