I am having a problem with reading a jpg file. I want to send the plain text value of the jpg image through a socket, so I opened the file in binary mode, thinking that that would work but it doesn't. This is my code:
我在阅读jpg文件时遇到问题。我想通过套接字发送jpg图像的纯文本值,所以我以二进制模式打开文件,认为这样可行,但事实并非如此。这是我的代码:
system("./imagesnap image.jpg");
ifstream image("image.jpg", ios::in | ios::binary);
char imageChar[1024];
string imageString;
while (getline(image, imageString))
{
for (int h; imageString[h] != '\0'; h++) {
imageChar[h] = imageString[h];
}
send(sock, imageChar, strlen(imageChar), 0);
for (int k = 0; imageChar[k] != '\0'; k++) {
imageChar[k] = '\0';
}
}
And here is my output:
这是我的输出:
????
As you can see, the file is not being opened in binary mode, or it is but its not working.
正如您所看到的,文件未以二进制模式打开,或者它不起作用。
Could anyone please help?
有人可以帮忙吗?
1 个解决方案
#1
3
Use read()
instead of getline()
. Be sure to use its return value.
使用read()而不是getline()。请务必使用其返回值。
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <fstream>
void SendFile(int sock) {
std::ifstream image("image.jpg", std::ifstream::binary);
char buffer[1024];
int flags = 0;
while(!image.eof() ) {
image.read(buffer, sizeof(buffer));
if (send(sock, buffer, image.gcount(), flags)) {
; // handle error
}
}
}
#1
3
Use read()
instead of getline()
. Be sure to use its return value.
使用read()而不是getline()。请务必使用其返回值。
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <fstream>
void SendFile(int sock) {
std::ifstream image("image.jpg", std::ifstream::binary);
char buffer[1024];
int flags = 0;
while(!image.eof() ) {
image.read(buffer, sizeof(buffer));
if (send(sock, buffer, image.gcount(), flags)) {
; // handle error
}
}
}