实验目的
- 了解文件编程原理
- 掌握文件编程,以及各种API的用法
实验内容
- 编写一个程序,在当前目录下创建用户可读写文件“hello.txt”,在其中写入“Hello, how are you”,关闭该文件。再次打开该文件,读取其中的内容并输出在屏幕上。
- 编写的程序使用创建、读写、关闭API
实验原理
- Linux的文件操作API涉及到创建、打开、读写和关闭文件。
- 系统命令相对于API来说是更高层级用户编程接口:系统调用并不是直接和程序员进行交互,它仅仅是一个通过软中断机制向内核提交请求,以获取内核服务的接口。在实际使用中程序员调用的通常是用户编程接口(API)
程序设计
#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "string.h"
#define length 100
int main()
{
int len;
char str[length];
int fd = open("./hello.txt",O_CREAT|O_RDWR,0700);
if(fd)
{
write(fd,"hello,how are you?",strlen("hello,how are you?"));
close(fd);
}
fd = open("./hello.txt",O_RDWR);
len = read(fd,str,length);
str[len]= '\0';
printf("%s\n",str);
close(fd);
return 0;
}
运行结果
实验总结
文件操作的API涉及到的创建、打开、读写和关闭文件,在实现过程中,只要创建一个txt文件和决定想要输入的内容依次进行读入,写出,关闭就可以