- read函数
man手册介绍
- 代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
int fd;
int n_open;
int n_write;
int n_read;
char *Buf="hello ubuntu";
fd=open("./file2",O_RDWR);
if(fd == -1){
printf("没有该文件,等待创建.....\n");
fd=open("./file2",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("创建成功并打开,fd=%d\n",fd);
}
}
n_write=write(fd,Buf,strlen(Buf));
if(n_write != -1){
printf("写入成功,写了%d个字节\n",n_write);
}
char *readBuf;//定义一个缓冲区
readBuf=(char *)malloc(sizeof(char)*n_write+1);//n_write是写入的字节数,readBuf大小就是写入了多少个字节数,加1保险点
// ssize_t read(int fd, void *buf, size_t count);
n_read=read(fd,readBuf,sizeof(readBuf));
if(n_read != 0){
printf("read %d个字节,内容是:%s\n",n_read,readBuf);
}
close(fd);
return 0;
}
- 结果出现问题
说明此时的n_read=-1;那是什么原因呢,在接下的学习中发现时光标的问题。(代码中当写完后光标停留在ubuntu的末尾u后面,所以是读不到) - 文件光标
lseek(int fd, off_t offset, int whence);//文件描述符,对wherence的偏移值,相对位置(固定位置)
SEEK_SET
The file offset is set to offset bytes.
SEEK_CUR
The file offset is set to its current location plus offset bytes.
SEEK_END
The file offset is set to the size of the file plus offset bytes.
-SEEK_SET指向文件的头
-SEEK_END指向文件的尾部
-SEEK_CUR指向文件的当前位置
- 可以利用这个光标来计算文件的大小
代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
int fd;
fd=open("./file2",O_RDWR);
int fileSize=lseek(fd,0,SEEK_END);
printf("大小为%d\n",fileSize);
return 0;
}
- 加了光标后的代码
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
int fd;
int n_open;
int n_write;
int n_read;
char *Buf="hello ubuntu";
fd=open("./file2",O_RDWR);
if(fd == -1){
printf("没有该文件,等待创建.....\n");
fd=open("./file2",O_RDWR|O_CREAT,0600);
if(fd > 0){
printf("创建成功并打开,fd=%d\n",fd);
}
}
n_write=write(fd,Buf,strlen(Buf));
if(n_write != -1){
printf("写入成功,写了%d个字节\n",n_write);
}
//lseek(int fd, off_t offset, int whence);
lseek(fd,0,SEEK_SET);//光标指向头部也可以写成lseek(fd,-12,SEEK_END/CUR);
char *readBuf;//定义一个缓冲区
readBuf=(char *)malloc(sizeof(char)*n_write+1);//n_write是写入的字节数,readBuf大小就是写入了多少个字节数,加1保险点
// ssize_t read(int fd, void *buf, size_t count);
n_read=read(fd,readBuf,n_write);//把fd的内容放到readBuf里面进行读取,读了n_write个
if(n_read != 0){
printf("read %d个字节,内容是:%s\n",n_read,readBuf);
}
close(fd);
return 0;
}
结果
-坚持的第三天,继续冲冲冲