今天的学习的任务是,学习文件的读取
和之前的内容一样,我们需要使用终端命令来查看文件读取的一些编程格式
man 2 read
可以看到和我们之前看到的write等差不多,大同小异,于是乎我们就可以编写我们的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h> //malloc函数,分配内存空间
int main()
{
int fd;
char *buf = "Hello Linux!";
fd = open("./file1",O_RDWR);
if(fd == -1)
{
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd > 0)
{
printf("create file1 success! \n");
}
}
printf("fd = %d\n",fd);
int n_write=write(fd,buf,strlen(buf));
if(n_write !=-1){
printf("write %d byte to file\n",n_write);
}
close(fd); //写入操作之后关闭
fd = open("./file1",O_RDWR); //重新打开,去读取,使光标回到初始位置,以重新读取,不然光标在输入的最后一个字节后开始读取的话,就会发生错误,没办法读取光标前面的内容,所以需要重新打开,让光标回到初始位置
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write); //readbuf无类型指针,不指向哪个空间,需要使用malloc函数分配
int n_read=read(fd,readbuf,n_write);
printf("read: %d ,context: %s",n_read,readbuf);
close(fd);
return 0;
}
我们写完代码后,编译试试:
read就是写入的字节数,context就是所输入的内容。
完成!