-2

I used the read() function to read the contents from a file but got a -1 return value. The file is not empty, I think it might be the problem of data type, but I am not sure. The contents of the file are like this: 1e00 000a 0600 0003 0100 0004 0300 0005 0800 0006 0900 0007 0b00 0003 0c00 0009 Thanks in advance.

#define swapFname "test.disk"

int main(int argc, char const *argv[])
{
    int diskfd;
    unsigned *buf;
    diskfd = open (swapFname, O_RDWR | O_CREAT, 0600);
    int location = (2-2) * 16 * 8 + 0*8; // 0
    int ret = lseek (diskfd, location, SEEK_SET);
    int retsize = read (diskfd, (char *)buf, 32);
    if (retsize < 0)
    { printf ("Error: Disk read returned incorrect size: %d\n", retsize); 
        exit(-1);
    }
}
Qiang Yao
  • 165
  • 12

2 Answers2

1

I was able to reproduce your issue locally. Having done so, I modified the program to be more informative about the nature of the problem: instead of printing a hand-rolled yet minimally-expressive error message, I used the perror() function to print a message that explains the specific nature of the error:

    if (retsize < 0) {
        perror("read");
        exit(-1);
    }

Running the resulting program produced this message:

read: Bad address

This seems to be reporting on the problem that @MichaelBurr noted in his comment: you have declared buf as a pointer to unsigned, but you have not assigned it to point to anything. As a result, it is a dangling pointer, and you should consider yourself lucky that the read function was able to recognize that, instead of (probably) clobbering random memory somewhere in your program's address space. It seems likely that you instead want to declare buf as an array, maybe something like this:

    unsigned buf[16];

With that additional correction, the program no longer reported an error from read(). That means it probably didn't have an error in open(), either, or in lseek(), but you ought to be testing each of those results individually.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

first I suggest to check you have open the file correctly, if the file have been opened check lseek if does not return -1, and later if you still wonder why you got -1 in read check errno in order to see the last error code.

Aneury Perez
  • 82
  • 2
  • 5