c - 使用 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");
}
该文件将被创建,但不会写入任何内容。没有出现任何错误。
解决方案
你肯定选择了艰难的方式来做到这一点。就像评论中建议的@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);
}
推荐阅读
- r - 无法在 Rstudio 中运行 DBF 文件
- javascript - ESLint no-multiple-empty-lines 规则类似但仅在对象属性范围内
- ruby-on-rails-3 - 如何在设计中的当前字段上添加值
- unit-testing - Mocha + Chai:测试失败后继续尝试所有断言
- python - 3D 中的 Alpha 形状 - 跟进
- nginx - NGINX 为什么我只在我的一个域名上获得 ERR_CERT_COMMON_NAME_INVALID?
- google-chrome - 为什么我得到 200(来自磁盘缓存)而不是 304 Not Modified?
- c++ - C++ 入门第 5 版。外部链接和函数重载
- python - Matplotlib:如何根据第三类列的颜色图绘制误差线图(不是 X 和 Y)
- reactjs - 如何访问 Redux Store 中的数据?