开发者

file read error: success

开发者 https://www.devze.com 2023-02-07 09:22 出处:网络
I have basic code as follows, fd = open(\"test.file\", O_RDONLY); if (read(fd, &tempch, 1) < 1) {

I have basic code as follows,

   fd = open("test.file", O_RDONLY);
   if (read(fd, &tempch, 1) < 1) {
         perror开发者_运维技巧("File Read Error");
         exit(1);
   }
   printf("We could read from the file\n");

the test.file is present in file system and has been granted with 777 rights. the program throws error "file read error: success"... could anybody tell the possible reason? thanks


It is perfectly normal for read() to return a zero count, it simply means that it has encountered the end of a file. If it returns a value less than zero, it is an error.

If -1 is returned, errno should be set, which will tell you what went wrong.

Does your file contain anything? Since you mentioned UNIX like permissions, the POSIX specification for read() should be useful for you.


You might want to check the return value of open and also how many bytes are present in test.file! If the file is of 0 bytes then return value of less than 1 is as expected.

From the read manual page

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal.


I'm not certain, but this

if (read(fd, &tempch, 1) < 1)

should almost certainly be

if (read(fd, &tempch, 1) < 0)
0

精彩评论

暂无评论...
验证码 换一张
取 消