0 为标准输入设备文件描述符
1 为标准输出设备文件描述符
2 为标准错误输出设备文件描述符
执行命令“chmod o+rw myfile”后,myfile文件的权限变化为
其他用户可读写myfile文件
案例
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
//请不要更改文件路径!!!
#define SRC_FILE_NAME "/data/workspace/myshixun/fileSystem/src/fileProgram/src_file"
//请不要更改文件路径!!!
#define DEST_FILE_NAME "dest_file"
#define OFFSET 10240
int main()
{
int src_file,dest_file;
unsigned char buff[BUFFER_SIZE];
int real_read_len;
//请在此处填入代码,使用合适的模式打开源目标SRC_FILE_NAME文件
src_file = open(SRC_FILE_NAME, O_RDONLY|O_CREAT);
//请在此处填入代码,使用合适的模式打开写入文件目标DEST_FILE_NAME文件,需要考虑到文件是否存在?
dest_file = open(DEST_FILE_NAME,O_WRONLY|O_CREAT,644);
if(src_file < 0 || dest_file < 0)
{
printf("Open file error!\n");
exit(1);
}
//请在此处填入代码,设置偏移量读取文件最后10KB数据
lseek(src_file,-OFFSET,SEEK_END);
while((real_read_len = read(src_file,buff,sizeof(buff))) > 0)
{
//请在此处填入代码,使用buff写入目标文件
write(dest_file, buff, real_read_len);
}
close(dest_file);
close(src_file);
return 0;
}
文件读read操作
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define rwmode 0
int main()
{
int fd;
char buffer[1024];
int n;
fd = open("/data/workspace/myshixun/case1/testFIle", rwmode);
if (fd < 0)
{
printf("Open file error!\n");
exit(1);
}
else
printf("open testFIle ok!\n");
//请使用read函数将其读入buffer中
n = read(fd,buffer,1023);
// printf("%d",n);
buffer[n] = '\0';
printf("%s\n", buffer,1024);
close(fd);
return 0;
}
另一种读写方式
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define resource_mode 0
#define destination_mode 0774
#define FILESIZE 1024
int main(int argc, char *argv[])
{
int resource_fd, destination_fd;
char buffer[FILESIZE], *p;
int readbytes, writebytes;
if (argc != 3)
{
printf("Usage:copy from resource file to destination file\n %s src_file dest_file\n", argv[0]);
exit(0);
}
if ((resource_fd = open(argv[1], resource_mode)) == -1)
{
perror("Can't open source file");
exit(0);
}
if ((destination_fd = creat(argv[2], destination_mode)) == -1)
{
perror("Can't create destination file");
exit(0);
}
// 请使用read函数读取前1024字节的内容读到缓冲区buffer中
while (readbytes = read(resource_fd,buffer,1))
{
p = buffer;
if ((readbytes == -1) && (errno != EINTR))
break;
else if (readbytes > 0)
{
// 请使用write函数读取到的前1024字节的内容写到目的文件中
while (writebytes = write(destination_fd,buffer,1))
{
if ((writebytes == -1) && (errno != EINTR))
break;
else if (writebytes == readbytes)
break;
else if (writebytes > 0)
{
p += writebytes;
readbytes -= writebytes;
}
}
if (writebytes == -1)
break;
}
}
close(resource_fd);
close(destination_fd);
return 0;
}