当前位置:网站首页>C中文件I/O的使用
C中文件I/O的使用
2022-07-27 04:42:00 【要学会下底传中】
C中的文件I/O主要就是有几个函数需要我们需要知道了解,有open函数,read函数,write函数,以及close函数。
open函数的使用
open:
打开一个文件
NAME
open, openat, creat - open and possibly create a file
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
pathname:路径名/文件名(不在当前目录,需要带路径)//是全部路径?
flags:文件标志,表示对文件的读写权限
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 可读可写
返回值:成功返回一个新的文件描述符
失败返回-1,同时error被设置
close函数的使用
close:
关闭一个文件
NAME
close - close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fd);
fd:文件描述符,我们打开的那个文件
read函数的使用
read:
从文件中读取内容
NAME
read - read from a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
fd:文件描述符,我们打开的那个文件
buf:我们将读到的内容存放的地方
count:读多少字节
返回值:成功返回读到的字节数(返回0时代表文件读完)
失败返回-1,同时error被设置
write函数的使用
write:
向文件中写入内容
NAME
write - write to a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
fd:文件描述符,我们打开的那个文件
buf: 我们要写入的内容
count: 写多少字节
返回值:成功返回写入的字节数(返回0,代表没有写进去)
失败返回-1,同时error被设置
当我们使用系统文件的时候,就是要注意使用那几个规定的头文件的,通过使用头文件里面的函数来完成我们想要的功能。
练习:
通过系统函数的调用完成将一个函数里面的东西,写到另一个函数里面去。
#include <sys/types.h>
#include <sys/stat.h>
#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd = open("nice.c",O_RDWR);
int fd2=open("cp1.c",O_RDWR);
char buf[5000]={
0};//这里其实是有一个缺陷的,这样做太浪费空间了。
while(1)
{
int read1;
read1= read(fd,buf,1);
write(fd2,buf,1);
if(read1==0)
{
close(fd2);
close(fd);
break;
}
}
return 0;
}
最后,做一下总结吧,就是其实通过系统I/O来操作文件其实就是操作fd文件操作符。
边栏推荐
猜你喜欢

STL 上头系列——list 容器详解

【搜索】DFS之连通性模型 + 搜索顺序

项目对接支付宝支付,内网穿透实现监听支付宝的支付成功异步回调通知

动态内存函数的介绍(malloc free calloc realloc)

CDH集群集成外部Flink(改进版-与时俱进)

会议OA之我的审批

C language - two dimensional array, pointer

使用Photoshop出现提示“脚本错误-50出现一般Photoshop错误“

Final Cut Pro中文教程 (2) 素材窗口的认识

Unity:Resource Merging、Static Batching、Dynamic Batching、GPU Instancing
随机推荐
OFDM 十六讲 2- OFDM and the DFT
【Acwing】第61场周赛 题解
Unity:Resource Merging、Static Batching、Dynamic Batching、GPU Instancing
Grid layout
背包问题dp
JS day 2 (variables, variable usage, naming rules, syntax extensions)
数字中国建设峰会闭幕,现场海量图片一览!
「Photoshop2021入门教程」调整图片到不同的长宽比
Simple static routing in ENSP
How do I reset Photoshop preferences? PS method of resetting preferences
Reproduce ssa-gan using the nine day deep learning platform
[error reporting] cannot read property 'parsecomponent' of undefined
The execution process of a select statement in MySQL
C language address book management system (linked list, segmented storage of mobile phone numbers, TXT file access, complete source code)
What if Photoshop prompts that the temporary storage disk is full? How to solve the problem that PS temporary storage disk is full?
Approval of meeting OA
自定义视口高度,多余的部分使用滚动
Dynamic routing configuration
Final Cut Pro中文教程 (1) 基础认识Final Cut Pro
Solution: how to use bash batch command in win10