1 Star 0 Fork 0

樊继强/Linux

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
system_file.c 1.57 KB
一键复制 编辑 原始数据 按行查看 历史
樊继强 提交于 2023-07-23 17:28 +08:00 . c和系统调用提供的的文件操作的练习
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/qq--1444354226/linux.git
git@gitee.com:qq--1444354226/linux.git
qq--1444354226
linux
Linux
master

搜索帮助