-------------------------------------资源来源于网络,仅供自学使用,如有侵权,联系我必删.
实验-关闭函数 close
close 函数介绍
任何一个文件在操作完成之后都需要关闭,这个时候需要调用 close 函数。
调用 close 函数之后,会取消 open 函数建立的映射关系,句柄将不再有效,占用的空间将被系统释放。
关闭文件close函数:
• int close(int fd);
第二:
实验-写函数 write
对文件进行写操作,write 函数使用的比较多。
• 写文件write函数:
• ssize_t write(int fd, const void *buf, size_t count);
– 参数fd表示:使用open 函数打开文件之后返回的句柄。
– 参数*buf表示:写入的数据
– 参数count表示:最多写入字节数
– 返回值:出错-1,;其它数值表示实际写入的字节数
//标准输入输出头文件
#include <stdio.h>
//文件操作函数头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
main()
{
int fd;
char *testwrite = "/bin/testwrite";
ssize_t length_w;
char buffer_write[] = "Hello Write Function!";
//进行写操作之前,必须得到文件的句柄,在这一行中使用 open 函数创建和打开文件“/bin/testwrite"。
if((fd = open(testwrite, O_RDWR|O_CREAT,0777))<0){
printf("open %s failed\n",testwrite);
}
//将buffer写入fd文件
length_w = write(fd,buffer_write,strlen(buffer_write));
if(length_w == -1)
{
perror("write");
}
else{
printf("Write Function OK!\n");
}
//调用 close 函数,将"/bin/testwrite"文件关闭
close(fd);
}
第三:
编译运行测试
1)在 Ubuntu 系统下,如下图所示,进入前面实验创建的目录“/home/linuxsystemcode/iofile”,将源码 write.c 拷贝进去
2)使用命令“arm-none-linux-gnueabi-gcc -o write write.c -static”编译 write.c 文件,如下图所示,使用命令“ls”可以看到生成了 write 可执行文件。
3)将编译成的可执行文件 write,拷贝到 U 盘,启动开发板,插入 U 盘,加载 U 盘,运行程序。如下图所示,打印出了 Write Function OK!。
4)在代码中定义的文件是"/bin/testwrite",使用 vi 编辑器打开文件,如下图所示,程序执行运行成功。