1.写(write)
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd = open("file",O_WRONLY|O_CREAT,0644);//以只写方式打开或不存在的话创建
if(fd < 0)
{
perror("open");
return 1;//程序失败
}
const char* msg = "hello world!\n";
int count = 5;
while(count--)//往文件里写5条程序
{
write(fd,msg,strlen(msg));
}
close(fd);//关闭文件
return 0;
}
编译通过会产生一个file,运行,打开file会看到5个hello world!
有几个文件描述符默认是被占用的(默认被打开),接下来将write()函数里的第一个参数改为“1”,默认往显示器上写。
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fd = open("file",O_WRONLY|O_CREAT,0644);//以只写方式打开或不存在的话创建
if(fd < 0)
{
perror("open");
return 1;//程序失败
}
const char* msg = "hello world!\n";
int count = 5;
while(count--)//往显示器上写5条程序
{
write(1,msg,strlen(msg));
}
close(fd);//关闭文件
return 0;
}
所以程序一旦运行起来,就是往显示器上写。