I am working on a client server application, where client compresses a 2MB data sends to the server, server receives the data uncompresses it and writes it to a file.
For some packets uncompression was failing and I added MD5 sum to both client side and server side code and also debugged using uncompression at the client side after compressing the data. The same parameters that passes for uncompress function in client side is failing with Z_DATA_ERROR in the server side. The data's MD5sum seems same. Am totally clueless what I could do next.
Server Side cod looks like this:
int ret = uncompress((Bytef*)unCompressedBuffer, &dwUncompressedBytes, (const Bytef*) receivedBuffer+525, dwBlockLength);
if (ret == Z_OK)
{
}
else
{
std::cout << " Uncompression failed for Block: " << iBlock << std::endl;
std::cout << " PacketType: 4" << " Block Number:" << iBlock << " Length:" << dwBlockLength << "Error:" << ret << std::endl;
PrintMD5SumResult((PBYTE)receivedBuffer+525, compressedSize-525);
std::cout << " Uncompressed MD5 Checksum:0";
PrintMD5SumResult((PBYTE)unCompressedBuffer, dwUncompressedBytes);
}
}
Client Code Looks like this:
int ret = compress2(l_pCompressData + 4, &destLen,
(const Bytef*) pBlockData, dwBlockSize, 6);
memcpy(m_pWriteBuffer+525, l_pCompressData, destLen);
m_dwWriteBytes = destLen+525;
std::cout << " \n Compressed MD5 Sum:0";
PrintMD5SumResult(m_pWriteBuffer, m_dwWriteBytes);
PrintMD5SumResult(m_pWriteBuffer+525, m_dwWriteBytes-525);
int ret = uncompress(m_pUnCompressData, &uncomLen, (const Bytef*)m_pWriteBuffer+525, destLen);
if(ret != Z_OK)
{
std::cout << " Uncompression has failed." << std::endl;
}
else
{
//std::cout << " UnCompressed MD5 Sum:0";
//PrintMD5SumResult((PBYTE)m_pUnCompressData, md5Output, dwBlockSize);
}
// Write the 2MB to the network
WriteDataOverNetwork(m_NetworkStream, m_pWriteBuffer, m_dwWriteBytes, &dwNumBytes, TRUE);
I narrowed down the problem to the following piece of code in zlib - but have a hard time understanding it. In the inflate() function, (ZSWAP32(hold)) != state->check) this statement is failing. Can someone help me out here? MD5sum used here is from Boton C++ library.
case CHECK:
if (state->wrap) {
NEEDBITS(32);
out -= left;
strm->total_out += out;
state->total += out;
if (out)
strm->adler = state->check =
UPDATE(state->check, put - out, out);
out = left;
if ((
#ifdef GUNZIP
state->flags ? hold :
#endif
ZSWAP32(hold)) != state->check) {
strm->msg = (char *)"incorrect data check";
state->mode = BAD;
break;
}
I also met this issue recently when I used zlib to do in-memory compression/decompression. The code is as follow:
size_t size = 1048576;
void *data;
void *comp_data;
uLong comp_data_len;
void *uncomp_data;
uLong uncomp_data_len;
void *temp;
int ret;
data = calloc(1, size); // data is filled with all zeros
comp_data_len = size * 1.01 + 12;
comp_data = calloc(1, size);
ret = compress(comp_data, &comp_data_len, data, size); //here ret is Z_OK.
uncomp_data_len = size;
uncomp_data = calloc(1, uncomp_data_len);
ret = uncompress(uncomp_data, &uncomp_data_len, comp_data, comp_data_len); //here ret is Z_OK
temp = calloc(1, 496);
for (i = 0; i < 100; i++)
{
//here fill some random data to temp
memcpy((char*)data + i * 100, temp, 496);
ret = compress(comp_data, &comp_data_len, data, size); //here ret is Z_OK.
ret = uncompress(uncomp_data, &uncomp_data_len, comp_data, comp_data_len); //here ret sometimes is Z_OK, sometimes is Z_DATA_ERROR!!!
}
I also traced the code and found that it failed at the statement "inflate() function, (ZSWAP32(hold)) != state->check)" too. So I cannot believe that the function uncompress is related to the data pattern. Am I wrong?
I also noticed that compress function calls deflate to do compression, deflate processes data every 64k, so need I split it to 64k blocks, compress each block one by one, then uncompress can work well?
i don't know whether it‘s the right answer ,maybe it help !my English is so poor,hope you can understand. perhaps the parameters convert to another has bugs . when they convert the info maybe lose ! i meet the same problem , after use the source code type the problem has been solved (Bytef\uLongf\ uLong,etc). the wed is Chinese you can use Google to translate.
http://www.360doc.com/content/13/0927/18/11217914_317498849.shtml
This is my test.the arry[] can be larger,same time the sour[]/dest[]/destLen/Len will be changed.using the source code type the problem has been solved. Hope will be helpful.
my code as follow:
#include <stdio.h>
#include "zlib.h"
int main(){
//the buffer can be larger
Bytef arry[] = "中文测试 yesaaaaa bbbbb ccccc ddddd 中文测试 yesaaaaa bbbbb ccccc ddddd 中文测试yesaaaaa bbbbb ccccc ddddd 中文测试 yes 我是一名军人!";
//buffer length
int size = sizeof(arry);
//store the uncompressed data
Bytef sour[2500];
//store the compressed data
Bytef dest[2500];
//压缩后的数据可能比源数据要大
unsigned long destLen = 2500;
//解压数据时因为不知道源数据大小,设置时长度尽可能大一些。以免出错
unsigned long Len = 2500;
int ret = -1;
ret = compress(dest,&destLen,arry,size);
//dest[destLen] = '\0';
printf("ret = %d\ndest = %s\n", ret, dest);
ret = uncompress(sour,&Len,dest,destLen);
//sour[size-1] = '\0';
printf("ret = %d\nsour = %s\n", ret, sour);
return 0;
}
Related
In a small utility I'm writing, I want to read a file record and:
look for the presence of an XOR checksum in the form *XX, where XX are hex digits
replace it if it's incorrect
add one if it's not present
So far, I'm only to the point of reading the file and looking for the checksum. The problem I'm up against is that std::string::find is not finding the * I know to be present; it returns npos every time.
The find() is on line 37. The first line read into strInput is:
$GPGGA,14240.99,2732.581,S,15301.947,E,1,06,3,65,M,37,M,-1.0,0006*6E\n
Here's the code:
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter input file name:\n";
std::string strFileName = "";
std::getline(std::cin, strFileName);
std::cout << "Filename entered: " << strFileName << '\n';
FILE* fp;
int nErrCode = EXIT_FAILURE;
fopen_s(&fp, strFileName.c_str(), "r+");
if (!fp)
{
std::string strErr = "Failed to open " + strFileName;
perror(strErr.c_str());
return nErrCode;
}
rewind(fp);
std::string strInput;
strInput.reserve(100);
std::string::size_type n;
do
{
fgets(&strInput[0], 99, fp);
std::cout << strInput.c_str();
//n = 0;
n = strInput.find('*');
if (n != std::string::npos)
std::cout << "Found checksum at position " << n;
else
std::cout << "Did not find checksum";
} while (!feof(fp));
}
Thanks in advance.
I've debugged this and all is well up to the find(). At that point, I can see that the return value is npos, even though I can see the value of strInput and verify that it contains an asterisk.
Is it possible to edit a .mm file before it gets compiled in AppCenter?
In an attempt to fix a build error, I want to find and replace a string in ../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm.
I tried using sed -i 's/oldString/newString/g' ../node_modules/react-native/React/CxxBridge/RCTCxxBridge.mm inside appcenter-pre-build.sh but it does not work.
Any help will be appreciated,
Thanks.
Not sure if this is your case, but I needed to update a version number on a complex project. To replace the counter of the current version with a new one, I considered updating the file with each build. After some versions of bash scripts, I realized that it's easier for me to write a console application in C with a couple of parameters to solve this problem. Works almost perfect for me. If you need I can share the simple code of this program.
Here is the C code that looks for a string in the file passed as a parameter and replaces the version number in it.
int main(int argc, char* argv[])
{
cout << "Version changer start\n";
if (argc < 2) {
cout << "There is no path argument. Version was no changed.";
return 1;
}
string sourcePath = argv[1];
string targetPath = sourcePath + ".tmp";
bool firstLine = true;
cout << sourcePath << endl;
ifstream sourceFile(sourcePath); // open file for input
ofstream targetFile(targetPath); // open file for output
string line;
while (getline(sourceFile, line)) // for each line read from the file
{
// looking for the desired line
if (line.find("public static String VER") != std::string::npos) { // replace "public static String VER" to your string definition code
line.replace(0, 32, "");
line.replace(line.length() - 2, 2, "");
int number = atoi(line.c_str());
number++; // In my case, I get an integer and add one to it
string v = to_string(number);
line = " public static String VER = \"" + v + "\";";
cout << v;
}
if (firstLine) {
targetFile << line;
firstLine = false;
}
else
targetFile << endl << line;
}
sourceFile.close();
targetFile.close();
remove(sourcePath.c_str());
if (rename(targetPath.c_str(), sourcePath.c_str()) != 0)
perror("Error renaming file");
else
cout << endl << "----------- done -----------\n";
}
I'm new to coding in C and C++, and I have a program with
an issue. When I (try) to run it, it gives me this error:
"No suitable constructor exists to convert from "char" to "std::string".
I'm not sure what it means. My code is an example of a simple
substitution cipher covered in the book "Cracking Codes with Python" by Al Sweigart.
I just want to replicate it in C++. Here's my code:
#include <iostream> // for communicating with user
#include <string>
using namespace std;
string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // all symbols
string encrypt(string msg, string key, string mode) {
string ca = symbols;
string cb = key;
string translated;
if (mode == "decrypt") {
ca, cb = cb, ca;
}
int index = 0;
for (index = 0; index < msg.length(); index++) {
cout << "index is " << index << endl;
int sindex = ca.find(msg[index]); // it works here
cout << "sindex is " << sindex << endl;
string cl = cb[sindex]; // the problem
translated += cl;
}
return translated;
}
int main() {
string msg = "";
string key = "";
string mode = "";
string ciphertext = ""; // our variables
cout << "Enter message: (no spaces please)\n";
cin >> msg;
cout << "Enter key (or \"none\" for using default):\n";
cin >> key;
if (key == "none") {
key = "QWERTYUIOPASDFGHJKLZXCVBNM";
}
cout << "Enter mode: (\"encrypt\" or \"decrypt\")\n";
cin >> mode;
ciphertext = encrypt(msg, key, mode);
cout << "The ciphertext is\n" << ciphertext;
}
For some reason it works with msg on line 17 but not with cb on line 19, even though
they're both std::string. The actual error is on line 19 with string cl = cb[sindex];.
Not even sure what's wrong. It works on line 17 int sindex = ca.find(/*The thing here*/msg[index]);.
(Maybe my Visual Studio 2019 has gone nuts.) If I replace cb with msg it still gives me the
same error. Maybe line 17 is a lucky line? Who knows? But please help, I'm so
confused!
I am writing a mpich program for parallel sorting. I need to use the mpi_gather interface, but it doesn't support passing vector of objects. So I use boost_serialization.
Implementation
I use boost_serialization to serialize the vector.
std::string serial_str;
boost::iostreams::back_insert_device<std::string> inserter(serial_str);
boost::iostreams::stream<boost::iostreams::back_insert_device<std::string>> s(inserter);
boost::archive::binary_oarchive send_ar(s);
//samples is the vector<object>
send_ar << samples;
s.flush();
int len = serial_str.size();
Then, I use mpi_gather to send all the serial_str to root process(data_recv).
char *data_recv = NULL;
if(myid == 0){
data_recv = (char*)malloc(sizeof(char) * (len_all+1));
data_recv[len_all] = '\0';
}
MPI_Gather((void*)serial_str.data(), len, MPI_BYTE, data_recv, len, MPI_BYTE, 0, MPI_COMM_WORLD);
Finally, I deserialize the data in data_recv.
boost::iostreams::basic_array_source<char> device(data_recv,len_all);
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> s(device);
boost::archive::binary_iarchive recv_ar(s);
std::vector<mdata> recv_vec;
recv_ar >> recv_vec;
My implementation is based on How to send a set object in MPI_Send
Problem
I can't deserialize the data in data_recv correctly. I printed the data_recv, then I found the data in data_recv is incorrectly formatted after mpi_gather. The second archive covered the first.(marked in bold)
serialization::archive
XylvXe-M X 00000000000000000000000000002595 DDDDFFFFCCCCBBBB111133332222DDDD333388888888FFFF2222serialization::archive000000000000000000023D0 EEEE7777EEEE44447777BBBB8888AAAA0000AAAAAAAAFFFF1111
XylvXe-M X 00000000000000000000000000002595 DDDDFFFFCCCCBBBB111133332222DDDD333388888888FFFF2222O#f&!O,t.b X 000000000000000000000000000023D0 EEEE7777EEEE44447777BBBB8888AAAA0000AAAAAAAAFFFF1111
The correct format should be:(no overlap so I can deserialize)
serialization::archive
XylvXe-M X 00000000000000000000000000002595 DDDDFFFFCCCCBBBB111133332222DDDD333388888888FFFF2222O#f&!O,t.b X 000000000000000000000000000023D0 EEEE7777EEEE44447777BBBB8888AAAA0000AAAAAAAAFFFF1111
serialization::archive
XylvXe-M X 00000000000000000000000000002595 DDDDFFFFCCCCBBBB111133332222DDDD333388888888FFFF2222O#f&!O,t.b X 000000000000000000000000000023D0 EEEE7777EEEE44447777BBBB8888AAAA0000AAAAAAAAFFFF1111
Question
Why did this happen? Is it because the mpi_gather isn't compatible with c++ object?
If someone could help me out, it would solve my big problem.
Thank you!
code
//processor rank, and total number of processors
int myid, world_size;
//for timing used by root processor
double startwtime = 0.0, endwtime;
//init MPI World
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
//get the processor name
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
MPI_Get_processor_name(processor_name,&name_len);
//read local data
std::vector<mdata> mdatas;
string data_path = "/home/jiang/mpi_data";
readAsciiData(data_path, mdatas);
cout <<"rank: "<<myid <<" mdata_vector.size(): "<<mdatas.size()<<endl;
//local sort according ASCII order
std::sort(mdatas.begin(), mdatas.end());
//regular sample
std::vector<mdata> samples;
for(int i=0; i<mdatas.size(); i=i+mdatas.size()/world_size){
samples.push_back(mdatas[i]);
}
//gather the regular samples
//passing data in byte stream by using boost serialization
std::string serial_str;
boost::iostreams::back_insert_device<std::string> inserter(serial_str);
boost::iostreams::stream<boost::iostreams::back_insert_device<std::string>> s(inserter);
boost::archive::binary_oarchive send_ar(s);
send_ar << samples;
s.flush();
int len = serial_str.size();
//int len = s.str().size();
int *pivot_lens = NULL;
if(myid == 0){
pivot_lens = (int*)malloc(sizeof(int) * world_size);
}
cout <<serial_str <<endl;
//first, gathering the lens and calculate the sum
cout << "rank " << myid << " on "<< processor_name << " is sending len: "<< len << endl;
MPI_Gather(&len, 1, MPI_INT, pivot_lens, 1, MPI_INT, 0, MPI_COMM_WORLD);
//calculate the sum of lens
int len_all = 0;
if(myid == 0){
for(int i=0;i<world_size;i++){
len_all = len_all + pivot_lens[i];
//cout << pivot_lens[i] << endl;
}
cout << "len_all:" << len_all << endl;
free(pivot_lens);
}
//then, gathering string of bytes from all the processes
char *data_recv = NULL;
if(myid == 0){
data_recv = (char*)malloc(sizeof(char) * (len_all+1));
data_recv[len_all] = '\0';
}
MPI_Gather((void*)serial_str.data(), len, MPI_BYTE, data_recv, len, MPI_BYTE, 0, MPI_COMM_WORLD);
// cout << serial_str <<endl;
if(myid == 0){
//deconstructe from byte of string to vector<mdata>
boost::iostreams::basic_array_source<char> device(data_recv,len_all);
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> s(device);
boost::archive::binary_iarchive recv_ar(s);
std::vector<mdata> recv_vec;
recv_ar >> recv_vec;
int count =0;
for(int i=0;i<len_all;i++){
cout<<data_recv[i];
count ++;
}
cout <<endl <<count ;
cout <<endl;
//cout << "rank " << myid << " gets the samples: " << recv_vec.size()<<endl;
iterateForTest(myid, recv_vec);
free(data_recv);
}
MPI_Finalize();
return 0;
Instruction for program:
Read the list of names from “names.txt” in the format “First Last”.
Sort the names based upon typical alphabetic order of peoples names based upon last name then first name.
Write the sorted list to a file called “sortednames.txt” in the format “Last, First”.
Here's my code: file data was stored in fullname array but now I am stuck on how to flip the first and last name in the array??
int main()
{
const int MAXNAMES = 100;
int value = 0;
string fullname[MAXNAMES];
ifstream inFile;
inFile.open("names.txt"); //open the file to excess the rainfall data
if (inFile.fail()) // testing the file
{
cout << "Error opening file. Please check that the file currently `enter code here`exist" << endl;
exit(1);
}
cout << "File successfully open" << endl;
while(!inFile.eof())
{
while(value < 100)
{
getline(inFile,fullname[value]);
value++;
}
}
return 0;
}
To flip the name around you could do the following:
string myString;
int spacePosition;
value = 0;
while(value < 100) {
myString = fullname[value];
spacePosition = myString.find(" ");
fullname[value] = myString.substr(spacePostion) + " " + myString.substr(0, spacePostion -1);
}