I need to send a txt file via socket connection when requested by client. The problem is I can’t figure how to convert from binary format to ASCII. With this code the client receive only junk characters.
ifstream file;
char output [logfilesize];
file.open( "log.txt" );
file >> output;
send(socket, output, sizeof(output), 0);
cout << output << endl;
file.close
Sorry if the question have been asked multiple time but after reading all post I could not figure how to make it work.
Thank’s!
Edit: Working code!
int lenght;
char * logf;
ifstream file;
file.open("log.txt");
file.seekg(0, ios::end);
lenght = file.tellg();
file.seekg(0, ios::beg);
logf = new char [lenght];
file.read(logf, lenght);
file.close();
cout.write (logf, lenght);
send(soc,logf , lenght, 0);
delete[] logf;
This
sizeof(output)will return the size of the original array you declared rather than the number of characters you read in via the stream operator. You can only use the stream in operator from the file stream if you know the file is text (i.e. you want to read a single delimited string). Else you should read the required number of bytes from the stream via theread()calls. If it is a string, then use thestrlen()function to determine the length of the string (NOTE: this will not work for binary data).