qfedu-linux-advanced-level/day2/homework/h6.c

52 lines
1.2 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个程序使用open系统调用创建一个新文件并使用write系统调用将用户从控制台输入的内容写入该文件直到用户输入 "quit"为止。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char const *argv[])
{
int fd = open("b.txt", O_RDWR | O_CREAT | O_TRUNC, 0600);
if (fd < 0)
{
perror("open");
return -1;
}
char buf[1024] = ""; // 初始化缓冲区
ssize_t input_len;
while (strcmp(buf, "quit\n") != 0) // 检查用户输入是否为"quit\n"
{
memset(buf, 0, sizeof(buf)); // 清空缓冲区
input_len = read(STDIN_FILENO, buf, sizeof(buf));
if (input_len < 0)
{
perror("read");
return -1;
}
if (strcmp(buf, "quit\n") != 0) // 检查用户输入是否为"quit\n"
{
int wrt = write(fd, buf, input_len);
if (wrt < 0)
{
perror("write");
return -1;
}
}
}
if (close(fd) < 0)
{
perror("close");
return -1;
}
return 0;
}