Lectura y escritura de datos binarios sobre puerto serie.

Así que busqué, y no pude encontrar exactamente lo que necesitaba. Necesito ayuda para leer y escribir datos binarios a través de un puerto serie, y agradecería cualquier consejo que pueda tener. Tenga en cuenta que hice una pregunta similar a esta anteriormente cuando estaba en una etapa diferente de este proyecto.

A continuación se presentan los programas. El primer programa abre un archivo "test.jpg", lo lee en modo binario y almacena el resultado en un búfer. Luego cierra el archivo, y se supone que envía ese archivo a través de un puerto serie.

El segundo programa crea un archivo llamado "testout.jpg", y se supone que lee los datos enviados desde el programa anterior.

Tengo el presentimiento de que el problema en mi código está en el segundo programa. ¿Quizás necesito usar fread para eso también? Lo intenté, pero no puedo descubrir cómo implementarlo para un puerto serie ya que soy relativamente nuevo en programación.

Muchas gracias por tu tiempo.

Escritura en serie:

    #include <stdio.h>   /* Standard input/output definitions */
    #include <string.h>  /* String function definitions */
    #include <unistd.h>  /* UNIX standard function definitions */
    #include <fcntl.h>   /* File control definitions */
    #include <errno.h>   /* Error number definitions */
    #include <termios.h> /* POSIX terminal control definitions */
    #include <stdlib.h>

    int main()
        {
                //writing
                int writeport = open_port("/dev/ttyUSB0");

                //open file

                FILE *file;
                char *buffer;
                int fileLen;

                file = fopen("test.jpg", "rb");

                //get file size

                fseek(file, 0, SEEK_END);
                fileLen = ftell(file);
                fseek(file, 0, SEEK_SET);

                buffer = (char *)malloc(fileLen + 1);

                //read file contents

                fread(buffer, fileLen, 1, file);
                fclose(file);

                int n = write(writeport, buffer, fileLen + 1);
                if (n < 0)
                        fputs("write() of bytes failed!\n", stderr);

                //closing ports
                close(writeport);
        }

        int open_port(char str[])
    {
        int fd = open(str, O_RDWR | O_NOCTTY | O_NONBLOCK); // ?? NDELAY or NONBLOCK?

      if (fd == -1)
      {
                        perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
                        fcntl(fd, F_SETFL, 0);

          struct termios options;
          tcgetattr(fd, &options); //this gets the current options set for the port

          // setting the options

          cfsetispeed(&options, B9600); //input baudrate
          cfsetospeed(&options, B9600); // output baudrate
          options.c_cflag |= (CLOCAL | CREAD); // ?? enable receicer and set local mode
          //options.c_cflag &= ~CSIZE; /* mask the character size bits */
          options.c_cflag |= CS8;    /* select 8 data bits */
          options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // choosing raw input
          options.c_iflag &= ~INPCK; // disable parity check
          options.c_iflag &= ~(IXON | IXOFF | IXANY); // disable software flow control
          options.c_oflag |= OPOST; // ?? choosing processed output
          options.c_cc[VMIN] = 0; // Wait until x bytes read (blocks!)
          options.c_cc[VTIME] = 0; // Wait x * 0.1s for input (unblocks!)

          // settings for no parity bit
          options.c_cflag &= ~PARENB;
          options.c_cflag &= ~CSTOPB;
          options.c_cflag &= ~CSIZE;
          options.c_cflag |= CS8;

          tcsetattr(fd, TCSANOW, &options); //set the new options ... TCSANOW specifies all option changes to occur immediately

      return (fd);
    }

Lectura en serie:

    #include <stdio.h>   /* Standard input/output definitions */
    #include <string.h>  /* String function definitions */
    #include <unistd.h>  /* UNIX standard function definitions */
    #include <fcntl.h>   /* File control definitions */
    #include <errno.h>   /* Error number definitions */
    #include <termios.h> /* POSIX terminal control definitions */

    int main()
        {
                //reading      
                int readport = open_port("/dev/ttyUSB1");

        //open resultant file

        FILE *file;
        //system("rm testout.jpg");
        file = fopen("testout.jpg", "wb");

                //trying to read one character at a time
                char buff;
                int n = 1;

           while (n > 0)
           {
                n = read(readport, &buff, 1);
                //printf("%c", buff, buff);

                **//I tried these three methods, with little success**

                //fprintf(file, "%c", buff);
                //fwrite(&buff, 1, 1, file);
                //write(file, &buff, 1);
           }

                //closing ports
                close(readport);
                fclose(file);
        }

        int open_port(char str[])
    {
        int fd = open(str, O_RDWR | O_NOCTTY | O_NONBLOCK); // ?? NDELAY or NONBLOCK?

      if (fd == -1)
      {
                        perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
                        fcntl(fd, F_SETFL, 0);

          struct termios options;
          tcgetattr(fd, &options); //this gets the current options set for the port

          // setting the options

          cfsetispeed(&options, B9600); //input baudrate
          cfsetospeed(&options, B9600); // output baudrate
          options.c_cflag |= (CLOCAL | CREAD); // ?? enable receicer and set local mode
          //options.c_cflag &= ~CSIZE; /* mask the character size bits */
          options.c_cflag |= CS8;    /* select 8 data bits */
          options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // choosing raw input
          options.c_iflag &= ~INPCK; // disable parity check
          options.c_iflag &= ~(IXON | IXOFF | IXANY); // disable software flow control
          options.c_oflag |= OPOST; // ?? choosing processed output
          options.c_cc[VMIN] = 0; // Wait until x bytes read (blocks!)
          options.c_cc[VTIME] = 0; // Wait x * 0.1s for input (unblocks!)

          // settings for no parity bit
          options.c_cflag &= ~PARENB;
          options.c_cflag &= ~CSTOPB;
          options.c_cflag &= ~CSIZE;
          options.c_cflag |= CS8;

          tcsetattr(fd, TCSANOW, &options); //set the new options ... TCSANOW specifies all option changes to occur immediately

      return (fd);
    }

Respuestas a la pregunta(1)

Su respuesta a la pregunta