mirror of
https://github.com/riba2534/TCP-IP-NetworkNote.git
synced 2026-04-13 18:00:00 +08:00
.
This commit is contained in:
28
ch01/low_open.c
Normal file
28
ch01/low_open.c
Normal file
@@ -0,0 +1,28 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
void error_handling(char *message);
|
||||
|
||||
int main()
|
||||
{
|
||||
int fd;
|
||||
char buf[] = "Let's go!\n";
|
||||
// O_CREAT | O_WRONLY | O_TRUNC 是文件打开模式,将创建新文件,并且只能写。如存在 data.txt 文件,则清空文件中的全部数据。
|
||||
fd = open("data.txt", O_CREAT | O_WRONLY | O_TRUNC);
|
||||
if (fd == -1)
|
||||
error_handling("open() error!");
|
||||
printf("file descriptor: %d \n", fd);
|
||||
// 向对应 fd 中保存的文件描述符的文件传输 buf 中保存的数据。
|
||||
if (write(fd, buf, sizeof(buf)) == -1)
|
||||
error_handling("write() error!");
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void error_handling(char *message)
|
||||
{
|
||||
fputs(message, stderr);
|
||||
fputc('\n', stderr);
|
||||
exit(1);
|
||||
}
|
||||
29
ch01/low_read.c
Normal file
29
ch01/low_read.c
Normal file
@@ -0,0 +1,29 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#define BUF_SIZE 100
|
||||
void error_handling(char *message);
|
||||
|
||||
int main()
|
||||
{
|
||||
int fd;
|
||||
char buf[BUF_SIZE];
|
||||
|
||||
fd = open("data.txt", O_RDONLY);
|
||||
if (fd == -1)
|
||||
error_handling("open() error!");
|
||||
printf("file descriptor: %d \n", fd);
|
||||
|
||||
if (read(fd, buf, sizeof(buf)) == -1)
|
||||
error_handling("read() error!");
|
||||
printf("file data: %s", buf);
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
void error_handling(char *message)
|
||||
{
|
||||
fputs(message, stderr);
|
||||
fputc('\n', stderr);
|
||||
exit(1);
|
||||
}
|
||||
Reference in New Issue
Block a user