开发者

Read returning zero in c++

I have written some text into a file using write() function, like this

if (write(3,buffer,1024) > 0)
        return true;

    return false;

When i manually saw in that file, I found the text that i put in buffer.

开发者_运维技巧

But when i try to read the text from the same file like this

if (read(3,temp,5) > 0)
           return true;

    return false;

Instead I printed the value returned by read. It is zero.

Can anyone explain what the problem is?

Thanks in advance


What file is 3? Do not hard-code literal numbers like that. Use the preset symbolic names like STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO, etc. or the file descriptor values you get from open() or create().

Anyway, what works all depends on how you opened them. If you open a file for writing only, you won't be able to read from it, etc. And if you just wrote to a file, you'll have to reset its file pointer to the beginning before you can read back what you wrote.

So show us some more of your code (e.g. how you open the file) and people will be able to help you. I guess you forgot to reset the file pointer. So try:

lseek(3, 0, SEEK_SET);

before you try to read from file 3. I still think a literal as file descriptor is very suspicious. It certainly doesn't seem very portable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜