为什么我无法从文件中读取它包含内容?

发布于 2025-02-03 21:32:07 字数 911 浏览 2 评论 0原文

我正在尝试创建一个函数,该函数复制一个给定文件描述符和文件名的文件:


int filedup(int fd1, char *cpyfile)
{
    int fd;
    size_t  rd;
    char    buff;
    
    if (fd1 < 0 || fd1 > OPEN_MAX)
        return (-1);
    if (!validfname(fname))
        return (-1);
    fd = open(cpyfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return (-1);
    rd = read(fd1, &buff, 1);
    while (rd > 0)
    {
        write(fd, &buff, 1);
        rd = read(fd1, &buff, 1);
    }
    close(fd);
    return (0);
}
int main(void)
{
    int fd;

    fd = open("/tmp/cpyfromfile", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return (-1);
    putstr_fd(strdup("hello world\n"), fd); 
    filedup(fd, "cpyfile");
    close(fd);
    return (0);
}

我尝试调试它,即使文件包含数据,问题也是rd == 0

$ cat ./cpyfile
$ (nothing)

我不确定有什么问题?我在做什么错?

I'm trying to create a function that duplicates a file given a file descriptor and a file name:


int filedup(int fd1, char *cpyfile)
{
    int fd;
    size_t  rd;
    char    buff;
    
    if (fd1 < 0 || fd1 > OPEN_MAX)
        return (-1);
    if (!validfname(fname))
        return (-1);
    fd = open(cpyfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return (-1);
    rd = read(fd1, &buff, 1);
    while (rd > 0)
    {
        write(fd, &buff, 1);
        rd = read(fd1, &buff, 1);
    }
    close(fd);
    return (0);
}
int main(void)
{
    int fd;

    fd = open("/tmp/cpyfromfile", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return (-1);
    putstr_fd(strdup("hello world\n"), fd); 
    filedup(fd, "cpyfile");
    close(fd);
    return (0);
}

I tried to debug it, and the problem was rd == 0 even though the file contains data.

$ cat ./cpyfile
$ (nothing)

I'm not sure what's the problem ? what am i doing wrong ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文