Home > front end >  simple code to read jpg files read retured 0 errno 0
simple code to read jpg files read retured 0 errno 0

Time:05-06

I have simple code that reads a .jpg file

But my read returns 0 and errno is 0. I just prefer of use read with read syscall.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int main()
{
    int fd=open("./a.jpg",O_RDONLY);
    int i=0;
    printf("%d %d %d\n",fd,errno,O_RDONLY);
    char buffer[1500];
    while(i<1500)
    {
        int valread=read(fd,&buffer[i],100);
        //printf("[valread = %d]\n",valread);
        i=i valread;
    }

    i=0;
    while(i<1500)
    {
        printf("%x ",buffer[i]);
        i  ;
    }
    return 0;
}

Can anyone point out whats wrong with above code.

CodePudding user response:

The loop

while (i < 1500) {
    printf("%x ", buffer[i]);
    i  ;
}

is not ideal, it will work fine if the buffer was correctly populated with 1500 bytes, otherwise the behavior is undefined.

I would suggest reading the entire file in one go, it's simpler and avoids the problems pointed out in the OP comments. You can then use the return value of read as the limit for the print loop, instead of the hardcoded 1500 value, i.e.:

int valread = read(fd, buffer, sizeof buffer);

while (i < valread) {
    printf("%x ", buffer[i]);
    i  ;
}

You didn't tell us what the value of fd is, if it's a positive integer it means the file was successfully opened, otherwise the open call failed. It can can also return 0, but that is reserved for stdin so it shouldn't, unless you closed stdin elsewhere. You can use perror to further diagnose a possible problem.

If the open call indeed returns a valid file descriptor, then everything is fine and if the output is not what you expect that should mean the file doesn't contain the expected data.

Sample code with the suggested changes:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    
    int fd = open("./a.jpg", O_RDONLY);

    if (fd < 0) {
        perror("Error");
        return EXIT_FAILURE;
    }

    int i = 0;
    char buffer[1500];

    int valread = read(fd, buffer, sizeof buffer);

    while (i < valread) {
        printf("%x ", buffer[i]);
        i  ;
    }
}
  •  Tags:  
  • c
  • Related