简体   繁体   中英

read from socket and write into file C++

Im looking for some working and efficient way of writing data, recieved by socket, into file. Right now im doing this:

if (!fStream.is_open()){
    cerr << "Unable to open file stream.\n";
    exit(EXIT_FAILURE);
}
char* recBuffer = new char [MAX_SIZE];

bzero(recBuffer, MAX_SIZE);
ssize_t recieved;
while ((recieved=read(s, recBuffer, MAX_SIZE))>0){
    fStream.write(recBuffer,MAX_SIZE);
    bzero(recBuffer, MAX_SIZE);
}

Problem of this implementation is ... lets say im recieving text file, when i write recieved data into file, file contains recieved data + NULLs from rest of the memory. If i write only recieved count, i see only NULLs in file.

ps Boost::Asio is not an answer for me :(.

Thanks

This line

fStream.write(recBuffer,MAX_SIZE);

should be

fStream.write(recBuffer,received);

And do not need the bzero bit on both lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM