代码拉取完成,页面将自动刷新
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#define FILENAME "testSYSTEM.txt"
#define SIZE 1024
void W(int o)
{
char* str="hello system";
int ans=5;
while(ans--)
{
char tmp[SIZE];
snprintf(tmp,sizeof(tmp),"%s:%d\n",str,ans);
write(o,tmp,strlen(tmp));//注意:字符以'\0'结尾是c语言的要求,不是文件的要求,所以strlen不需要+1补上最后的'\0'
}
}
void R(int o)
{
char tmp[SIZE]={'\0'};
read(o,tmp,sizeof(tmp));//系统调用的read会一次性读完文件的全部内容,不会如同fread一样一行一行的读取
printf("%s",tmp);
}
void A(int o)
{
char* str="hello system aaaaaaaaaaaaaaa";
int ans=2;
while(ans--)
{
char tmp[SIZE];
snprintf(tmp,sizeof(tmp),"%s:%d\n",str,ans);
write(o,tmp,strlen(tmp));
}
}
int main()
{
//没写但需要注意的点,open,write,read等系统调用的返回值需要判断
umask(0000);//系统调用提供的文件操作open受权限掩码umask的影响
//打开文件,第二个参数为标志,主要使用O_RDONLY(读),O_WRONLY(写),O_CREAT(创建),O_TRUNC(清空),O_APPEND(追加)
//多个标志中间用'|'连接,使用O_CREAT(创建)需要初始权限,且注意更改umask
int o=open(FILENAME,O_RDONLY);//该情况与c库的"r"类似
R(o);
//int o=open(FILENAME,O_WRONLY|O_CREAT|O_TRUNC,0666);//该情况与c库的"w"类似
//W(o);
//int o=open(FILENAME,O_WRONLY|O_CREAT|O_APPEND,0666);//该情况与c库的"a"类似
//A(o);
//关闭文件
close(o);
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。