首页 > 解决方案 > 使用 write() 将 char* 从用户输入写入文件

问题描述

我正在尝试编写一个函数,该函数从标准输入获取路径并将该路径保存到文件中。尽管进行了多次尝试,但我对如何正确地做到这一点失去了任何感觉。有人可以告诉我怎么做吗?这是我的代码:

void char_to_file(const char *pathname, const char *dest)
{
        int fd_1;
        if (fd_1 = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0666) == -1)
                custom_error_shout("OPEN FD_1");
        while (*(pathname) != '\0')
        {
                *(pathname++);
                if (write(fd_1, &pathname, 1) == -1)
                        custom_error_shout("WRITE TO FILE");
        }

        if (close(fd_1) == -1)
                custom_error_shout("CLOSE FD_1");
}

该文件将被创建,但不会写入任何内容。没有出现任何错误。

标签: csystem-calls

解决方案


你肯定选择了艰难的方式来做到这一点。就像评论中建议的@tadman 一样,试试这个:

void char_to_file(const char *pathname, const char *dest)
{
    FILE *fp;
    fp = fopen(dest, "w");
    if (fp == NULL)
    {
        custom_error_shout("Something went wrong opening the file");
        return;
    }

    if (fputs(pathname, fp) == EOF)
        custom_error_shout("Something went wrong writing to the file");

    fclose(fp);
}

推荐阅读