I am just trying to implement a simple web server in C++. For that depending on the request the web server fetches data from server. For that I am using
int main()
{
std::ifstream file("/home/chaitanya/cpp/net/hello");
int length;
char *buffer;
if(file.is_open())
{
std::cout << "File is open\n";
file.seekg(0, std::ios::end);
length = file.tellg();
file.seekg(0, std::ios::beg);
buffer = new char[length];
file.read(buffer, length);
file.close();
}
printf("Data:\n\n%s\n", buffer);
delete[] buffer;
return 0;
}
This working fine for small files. Even i am sending the whole file data irrespective of its size thru the socket. Is it a better approach ?
For instance, if file size is huge ? I guess it would be better to send a specific chunk of data at a time.
Can u guys plz suggest as to which approach would be good (or) any other better/faster approaches used by web servers ?
Thanks in advance. 🙂
Almost in every OS you have a better OS dependent option for sending a file over a socket, for example in
linuxyou have sendfile, inWindowsyou have TransmitFile and …, but if you want to have a simple portable solution, I will derive a class fromstd::ostreamthat send data to the socket and then use this:using this technique I can send multi giga byte files without any problem!