使用write函数需要包含以下头文件:
#include
ssize_t write(int fd, const void *buf, size_t count);
附加:一般将数据写入文件中后需关闭文件,这里需要调用关闭(close)函数,其包含的头文件与写入函数一样,函数定义格式也比较简洁,如下:
int close(int fd);
参数解读:调用该函数时,只需将需要关闭文件的文件描述符fd传进来即可实现关闭。
int fd:fd为创建文件的文件描述符
const void *buf:这里为无类型的指针,通常对他进行强转成字符串:buf为要写入的字节
size_f count:写入字节的长度
整体流程:从定义的buf中写入count个字节并传到文件描述符fd对应的文件。
写入成功后会返回写入字节的个数(整型数);写入失败会返回-1。
- #include
- #include
- #include
- #include
- #include
-
- int main()
- {
- int fd;
- char *buf = "Hello Word";//将无类型指针强制转换并输入字节
- 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,它能计算出字符串的有效长度,而这里的buf是char型指针,如果用sizeof只能计算出char型在系统中的长度(8个字节),若输入的字符串超过8位,那么使用sizeof只能输入前8位。

![]()
使用读取函数时需包含以下头文件
#include
ssize_t read(int fd, void *buf, size_t count);
int fd:fd为创建文件的文件描述符
const void *buf:这里为无类型的指针,通常对他进行强转成字符串:buf为要读取的字节
size_f count:读取字节的长度
整体流程:从文件描述符fd读取count个字节的数据传到buf的缓冲区中。
读取成功后会返回读取字节的个数(整型数);读取失败会返回-1。
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main()
- {
- int fd;
- char *buf = "Hello Word";
-
- fd = open("./file1",O_RDWR);//文件删除,文件描述符返回值为-1
-
- if(fd == -1)
- {
- printf("open file1 failed\n");
- fd = open("./file1",O_RDWR|O_CREAT,0600);//重新建立一个file1,此时文件描述符返回值大于0
- if(fd > 0)
- {
- printf("creat file1 success\n");
- }
- }
- printf("open success:fd = %d\n",fd);
-
- int n_write = write(fd,buf,strlen(buf));//定义一个整型变量存放write返回的文件描述符的值(写入字节个数)
- if(n_write != -1)
- {
- printf("write %d byte to file1\n",n_write);
- }
- close(fd);//由于光标问题,写完之后光标在最后面 此时read从光标位置开始读取,并不会读取写入文件中的字符串,需关闭文件并重新打开
- fd = open("./file1",O_RDWR);
-
- char *readBuf;
- readBuf = (char *)malloc(sizeof(char)*n_write+1);//对指针进行开辟内存空间,其读取的字节数为写入的字节数,其大小为char型,可用写入字节个数乘以char的值即为读取个数,此时存放的是字符串
- int n_read = read(fd,readBuf,n_write);//定义一个整型变量存放read返回的文件描述符的值(读取字节个数)
- printf("read byte is %d,context is %s\n",n_read,readBuf);
- close(fd);
-
- return 0;
- }
