今天学习的内容有很多,得了新冠之后真的很不舒服,吃饭也没有味道,真的特别难受,为了尽快恢复,前几日还花费了好长时间锻炼恢复身体,但是依然身体酸软无力,还不如在家好好学习。。
——————————————————————————————-——
写入文件:
如同打开创建文件一样,我们使用命令查看写入文件的格式:
man 2 write
其中*buf是个缓冲区,无类型指针
count是写入文件的大小字节数。
于是我们在我们的C文件中编写代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h> //write
#include <string.h> //strlen
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("creat file1 success!\n");
}
}
printf("open success :fd= %d\n",fd);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
这边需要注意的是,我用了strlen,本来想使用sizeof,但是我发现居然只显示了 Hello Li 八个字符,因此我是用strlen,这边我们需要使用命令
man strlen
查看一下头文件需要如何用,
所以我们头文件需要使用 #include <string.h>
OK,我们运行一下看看:
完成!get 写入技能!