文件IO完结

This commit is contained in:
lzy
2024-04-28 02:06:33 +08:00
parent d2136d1f26
commit d75a518c0f
4 changed files with 150 additions and 4 deletions

27
Chapter13/io/sys/ab.c Normal file
View File

@@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
putchar('a');
write(1, "b", 1);
putchar('a');
write(1, "b", 1);
putchar('a');
write(1, "b", 1);
/**
* 这里标准IO与文件IO混用
* 实际输出:
* bbbaaa
*
* 命令 strace
* 可以跟踪系统调用
*
*/
exit(0);
}

51
Chapter13/io/sys/dup.c Normal file
View File

@@ -0,0 +1,51 @@
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define FNAME "/tmp/out"
int main(int argc, char **argv)
{
int fd;
/***
* bug:
* 1. 假如默认没有1这里有bug。
* 2. 假如这个非原子操作的操作的过程,有可能被别的进程影响。
*/
fd = open(FNAME, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0)
{
perror("open");
exit(1);
}
// close(1);
// dup(fd);
dup2(fd, 1);
// 使用 dup2 原子操作
// 且dup2如果两个参数相等不会做任何事
// !!!
if (1 != fd)
close(fd);
#if 0
close(1);
fd = open(FNAME, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0)
{
perror("open");
exit(1);
}
#endif
/********************************************************************/
puts("hello!");
// TODO: 将sdtout回到终端
exit(0);
}

View File

@@ -4,6 +4,11 @@
#include <unistd.h>
#define BUFSIZE 1024
/**
* 可以用 time 命令找到 BUFSIZE 最佳值
*
* time ./mycpy /etc/services /tmp/out
*/
int main(int argc, char **argv)
{
@@ -47,6 +52,7 @@ int main(int argc, char **argv)
pos = 0;
while (len > 0)
{
/* 可能没写完被别的中断打断 */
ret = write(dfd, buf + pos, len);
if (ret < 0)
{