#include <unistd.h>
int main()
{
char str[5];
char c;
c = '\n';
read(STDIN_FILENO,str,5);
write(STDOUT_FILENO,str,4);
write(STDOUT_FILENO,&c,1);
return 0;
}
程序2:把一个文件的内容拷贝到另一个文件,这里主函数包含了参数,也可以自己在主函数中强定义文件名(看下一个程序)
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define BUTTER_SIZE 1024
int main(int argc,char **argv)
{
int from_fd,to_fd;
int bytes_read,bytes_write;
char butter[BUTTER_SIZE];
char *ptr;
if(argc != 3) // 一个进程启动,自动打开三个文件
{
printf("usage:from_file and to_file\n");
exit(-1);
}
from_fd = open(argv[1],O_RDONLY);
if(from_fd == -1)
{
printf("open error");
exit(-1);
}
to_fd = open(argv[2],O_WRONLY | O_CREAT,S_IWUSR | S_IRUSR);
if(to_fd == -1)
{
printf("open2 error");
exit(-1);
}
while(bytes_read = read(from_fd,butter,BUTTER_SIZE))
{
if(bytes_read == -1 && errno != EINTR)
{
break;
}
else if(bytes_read > 0)
{
ptr = butter;
while(bytes_write = write(to_fd,ptr,bytes_read))
{
if(bytes_write == -1 && errno != EINTR)
{
break;
}
else if(bytes_write == bytes_read)
{
break;
}
else if(bytes_write > 0)
{
ptr += bytes_write;
bytes_read -= bytes_write;
}
}
if(bytes_write == -1)
{
break;
}
}
}
close(from_fd);
close(to_fd);
return 0;
}
程序3: 函数名已经强定义好,其他和程序2相同,剩下的程序都在使用文件描述符 如from_fd,to_fd
int main()
{
int from_fd,to_fd;
int bytes_read,bytes_write;
char butter[BUTTER_SIZE];
char *ptr;
from_fd = open("a.txt",O_RDONLY);
if(from_fd == -1)
{
perror("open error");
exit(-1);
}
to_fd = open("d.txt",O_WRONLY | O_CREAT,S_IWUSR | S_IRUSR);
if(to_fd == -1)
{
perror("open2 error");
exit(-1);
}
程序4:键盘输入3个hello,写入到另一个文件中,以每行显示一个hello为例,第二个for循环读出这个文件的内容,读之前注意写的时候指针已经变化到尾部
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
int fd;
int n_write,n_read;
char read_buffer[5];
char write_buffer[5];
int i;
char c;
fd = open("hello.txt",O_CREAT | O_RDWR,0644); //如果读fd文件中的内容,这个地方不能只定义成只写
if(fd == -1)
{
perror("open error");
exit(-1);
}
for(i = 0;i < 3;i++)
{
memset(write_buffer,0,sizeof(write_buffer));
read(STDIN_FILENO,write_buffer,5);
read(STDIN_FILENO,&c,1);
write(fd,write_buffer,5);
write(fd,&c,1);
}
lseek(fd,0,SEEK_SET); //这个地方写到fd中指针指到了尾,需要将指针移动到头,开始读文件
for(i = 0;i < 3;i++)
{
memset(read_buffer,0,sizeof(read_buffer));
memset(&c,0,sizeof(c));
read(fd,read_buffer,5);
write(STDOUT_FILENO,read_buffer,5);
read(fd,&c,1);
write(STDOUT_FILENO,&c,1);
}
close(fd);
return 0;
}