0
点赞
收藏
分享

微信扫一扫

系统级程序设计 2.1: Linux文件系统与操作

90哦吼 2022-05-03 阅读 58

文章目录

一、前言

二、本节所涉及的函数

三、案例

四、总结


一、前言

系统级程序设计的第一节课,本课程学习的是对接操作系统的程序设计,是相对统筹的一门学科,第一颗=课学习和考察的是文件操作。

二、函数

1.1 open函数

#include <fcntl.h>
int open(const char *pathname, int flags[, mode_t mode);

open函数参数说明:

    pathname:待打开文件的文件路径名;
    flags:访问模式,常用的宏有:
    – O_RDONLY:只读
    – O_WRONLY: 只写
    – O_RDWR: 读写
    – O_CREAT: 创建一个文件并打开
    – O_EXCL: 测试文件是否存在,不存在则创建
    – O_TRUNC: 以只写或读写方式成功打开文件时,将文件长度截断为0
    – O_APPEND: 以追加方式打开文件

例: 创建一个文件

open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode);
or
int create(const char *pathname, mode_t mode);

1.2 read函数

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

特殊说明: read函数从设备或网络中读数据,如从终端读取数据,终端写入数据没回车,这些数据不会传给read函数,read函数就会一直阻塞;如从网络端读取数据,网络通信的socket文件没有数据,read函数同样会阻塞。 

1.3 write函数

#include <unistd.h>
ssize_t write(int fd, void *buf, size_t count);

 write函数参数说明: 同read函数
返回值说明: 返回写入的字节数或者-1并设置errno
特殊说明: 向终端或网络端写数据时,可能会进入阻塞状态

1.4 lseek函数

#include <unistd.h>
ssize_t write(int fd, off_t offset, int whence);

lseek函数参数说明:

    fd: 从open或create函数返回的文件描述符
    offset: 对文件偏移量的设置,参数可正可负
    whence: 控制设置当前文件偏移量的方法
    – whence = SEEK_SET: 文件偏移量被设置为offset
    – whence = SEEK_CUR: 文件偏移量被设置为当前偏移量+offset
    – whence = SEEK_END: 文件偏移量被设置为文件长度+offset

返回值说明:

    设置成功:返回新的偏移量
    不成功:-1

1.5 close函数

#include <unistd.h>
int close(int fd);

返回值说明:

  • 成功:返回0
  • 不成功:-1

三、案例

案例1: 使用open函数打开或创建一个文件,将文件清空,使用write函数在文件中写入数据,并使用read函数将数据读取并打印。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){
	int tempFd = 0;
	char tempFileName[20] = "test.txt";
	//Step 1. open the file.
	tempFd = open(tempFileName, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG);
	if(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	//Step 2. write the data.
	int tempLen = 0;
	char tempBuf[100] = {0};
	scanf("%s", tempBuf);
	tempLen = strlen(tempBuf);
	write(tempFd, tempBuf, tempLen);
	close(tempFd);
	//Step 3. read the file
	tempFd = open(tempFileName, O_RDONLY);
	if(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	off_t tempFileSize = 0;
	tempFileSize = lseek(tempFd, 0, SEEK_END);
	lseek(tempFd, 0, SEEK_SET);
	while(lseek(tempFd, 0, SEEK_CUT)!= tempFileSize){
		read(tempFd, tempBuf, 1024);
		printf("%s\n", tempBuf);
	}//of while
	close(tempFd);
	return 0;
}//of main

 运行过程:

 四、总结

应老师要求第一次使用csdn社区发表文章,还是有很大的收获,能分享的自己的学习心得并记录和分析学习过程中出现的问题。

1.注意多使用注释,能使自己的代码变得简单易懂,也更容易分析代码结构。

2.注意函数后的左大括号紧贴函数,使代码更加规范,紧凑。

3.熟悉了解了文件操作相关的知识

举报

相关推荐

0 条评论