read 返回 -1, 为什么?

wllabs 2018-04-19 12:20:58
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main()
{
char file[] = "/root/b.c";
int flags = O_RDONLY;
flags |= O_DIRECT;
flags |= O_SYNC;
int fd = open(file, flags);
char buff[4096];
printf("%d\n", read(fd, buff, 2));
while(read(fd, buff, 2) > 0)
{
printf("aaaa\n");
printf("%s", buff);
}
close(fd);
}



我这样读文件,read 为什么返回 -1。
哪里错了。
...全文
2417 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
白色一大坨 2018-05-04
  • 打赏
  • 举报
回复
O_DIRECT这种东西,要搞明白含义再使用。
leetow2006 2018-05-04
  • 打赏
  • 举报
回复
linux下返回-1,一般都是错误的。可以用strerror(errno)来获取错误的详细信息
自信男孩 2018-04-19
  • 打赏
  • 举报
回复
建议判断一下open的返回值,即需要判断文件是否成功打开。 很有可能是文件打开失败
幻夢之葉 2018-04-19
  • 打赏
  • 举报
回复
引用 2 楼 wllabs 的回复:
[quote=引用 1 楼 cfjtaishan 的回复:] 建议判断一下open的返回值,即需要判断文件是否成功打开。 很有可能是文件打开失败
打印了下是 3。 有值, 我把这个 flags |= O_DIRECT 去掉就可以读了。这是为什么? [/quote] https://blog.csdn.net/axw2013/article/details/70242228
幻夢之葉 2018-04-19
  • 打赏
  • 举报
回复
引用 2 楼 wllabs 的回复:
[quote=引用 1 楼 cfjtaishan 的回复:] 建议判断一下open的返回值,即需要判断文件是否成功打开。 很有可能是文件打开失败
打印了下是 3。 有值, 我把这个 flags |= O_DIRECT 去掉就可以读了。这是为什么? [/quote] https://blog.csdn.net/axw2013/article/details/70242228
自信男孩 2018-04-19
  • 打赏
  • 举报
回复
#include<stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

int main()
{
    char file[] = "/root/b.c";
    int flags = O_RDONLY, ret;
    flags |= O_DIRECT;
    flags |= O_SYNC;
    int fd = open(file, flags);
    if (fd < 0)
        return 1;
    char buff[4096];
    ret = read(fd, buff, 2);
    if (ret < 0)
        printf("%s\n", strerror(errno));
    else if (ret > 0)
        puts(buff);
    //printf("%d\n", read(fd, buff, 2));
    while(read(fd, buff, 2) > 0)
    {
        printf("aaaa\n");
        printf("%s", buff);
    }
    close(fd);

    return 0;
}
用strerror(errno)定位是什么原因导致的return -1
赵4老师 2018-04-19
  • 打赏
  • 举报
回复
wllabs 2018-04-19
  • 打赏
  • 举报
回复
引用 1 楼 cfjtaishan 的回复:
建议判断一下open的返回值,即需要判断文件是否成功打开。 很有可能是文件打开失败
打印了下是 3。 有值, 我把这个 flags |= O_DIRECT 去掉就可以读了。这是为什么?

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧