open打开\创建一个文件,进行写读操作(7.13)
作者:互联网
open
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("./d.txt", O_RDWR | O_CREAT, 0666);
if(fd < 0)
{
perror("open");
}
printf("fd = %d\n", fd);
close(fd);
return 0;
}
write
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>
int main()
{
int fd = open("./d.txt", O_RDWR | O_CREAT, 0666);
if(fd < 0)
{
perror("open");
}
printf("fd = %d\n", fd);
char msg[128] = "正在写文件~";
write(fd, msg, strlen(msg));
close(fd);
return 0;
}
read
#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include<sys/types.h>
#include <string.h>
int main()
{
int fd = open("./d.txt", O_RDWR | O_CREAT, 0666);
if(fd < 0)
{
perror("open");
}
printf("fd = %d\n", fd);
char msg[128] = "";
read(fd, msg, sizeof(msg));//此时文件中已经有之前写过的字符存在了,所以可以直接读取
puts(msg);
close(fd);
return 0;
}
执行结果在word文档中
标签:7.13,int,写读,fd,printf,msg,include,open 来源: https://blog.csdn.net/HanLongXia/article/details/118708798