无法读取 JPG C++的纯文本值

Can't Read Plain Text Value of JPG C++

本文关键字:文本 C++ 读取 JPG      更新时间:2023-10-16

我在读取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] != ''; h++) {
        imageChar[h] = imageString[h];
    }
    send(sock, imageChar, strlen(imageChar), 0);
    for (int k = 0; imageChar[k] != ''; k++) {
        imageChar[k] = '';
    }
}

这是我的输出:

????

正如您所看到的,该文件不是以二进制模式打开的,或者它是但不工作。

有人能帮忙吗?

使用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
    }
  }
}