学习linux系统函数read.
用read读取一个文件并将内容输出到屏幕上:
/*************************************************************************
> File Name: MyOpen.cpp
> Author: xuchen_allen
> Mail: [email protected]
> Created Time: 2019年01月29日 星期二 10时11分33秒
************************************************************************/
#include<iostream>
using namespace std;
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
//打开一个已经存在的文件
int fd = open("english.txt",O_RDWR);
if(fd == -1){
perror("open file:");
exit(1);
}
//读取文件内容:
char *buf = new char[2048];
int count = read(fd,buf,sizeof(buf));
if(count==-1){
perror("read fail");
exit(1);
}
while(count){
cout<<buf;
count = read(fd,buf+count,sizeof(buf));//此处要将buf往后移,要不然就会死循环
}
//关闭文件:
int ret = close(fd);
cout<<"ret="<<ret<<endl;
return 0;
}
函数