c - 打印到文本文件但文件仍然为空
问题描述
#include <stdio.h> //for printf
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
//#define STDOUT_FILENO 1
// define STDERR_FILENO 2
int main(){
// mode_t mode = S_IROTH | S_IRUSR | S_IWUSR;
mode_t mode = S_IRUSR | S_IWUSR;
close(1);
int fildes = open("hello_world.txt", O_CREAT | O_TRUNC | O_RDWR, mode);
printf("Hi! My Name is \n" );
close(fildes);
return 0;
}
据我所知,“嗨!我的名字是”应该打印到“hello_world.txt”。它在我教授提供的 Linux 虚拟机中运行良好。但是在我的机器中(我在 vscode 中使用远程 WSL),“hello_world.txt”是空的。我可以解决这个问题吗?
解决方案
printf
不一定写什么。通常,它缓冲数据并延迟write
s 直到缓冲区已满。 stdout
进程退出时会自动刷新,但在此之前您已经关闭了文件描述符,因此write
失败。fflush(stdout)
在关闭底层文件描述符之前尝试。(这假设 hackyopen
实际上为您提供了标准输出的底层文件描述符。这应该发生并且在大多数情况下会发生,但肯定不能保证。freopen
如果您想可靠地执行此操作,您应该使用。)
推荐阅读
- regex - perl6 正则表达式:匹配除 . 和 ”
- android - lateinit 属性 resultReceiver 尚未初始化
- php - 从PHP和andriod studio编码时的Json对象img url问题
- modelica - 使用包含数组的三个方程编译代码时出现初始化错误
- node.js - 节点 IPC 如何在 2 个进程之间工作
- c - 递归删除链表中的重复元素
- python-3.x - 无法在画布中创建圆圈
- r - 如何使用R从excel中的单元格中提取多列?
- ios - Scrollview 内的 UIImageView - 缩放时偏离中心
- c - 在这个例子中我需要考虑字节顺序吗?