系统级程序设计(作业一)

通过上课学习了linux下使用c语言进行文件操作等,以及一些简单的文件操作的函数文件操作函数
open()函数
该函数存在于系统函数库fcntl.h中,功能为:打开或者创建一个文件。形式如下,int open(const char *pathname , int flags[,mode_t mode]);
pathname为要打开文件的文件路径名;flags为文件的访问模式,一般使用一组宏表示; mode是可选属性,和Linux终端命令中的chmod相似,给文件一定的读写权限。read()函数
该函数存在于函数库unistd.h中,功能为:从已打开的设备或者文件中读取数据。形式如下,ssize_t read(int fd,void * buf,size_t count);
fd    为从open或create函数返回的文件描述符,简单来说fd就是open一个文件后赋的值。
buf    缓冲区,就是把文件中的内容按指定大小存在buf中后续进行输出
count    最大读取的长度,即指定要读去数据的长度或者大小
write()函数
与read()相似,不过一个是读一个是写,参数也大体相同。形式如下,ssize_t write(int fd,const void * buf,size_t count);
lseek()函数
lseek()存在于函数库unistd.h中,功能:相当于一个光标的位置,即偏移量,它决定了文件读写的起始位置。形式如下,off_t lseek(int fd, off_t offset, int whence);
fd与read()中的一样,不赘述了;offset是对当前偏移量的设置,可正可负;whence为控制偏移量的方法。close()函数
打开的文件在操作结束后使用close()释放缓存。形式如下,int close(int fd);代码案例
#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_CUR)!= tempFileSize){
        read(tempFd, tempBuf, 1024);
        printf("%s\n", tempBuf);
    }//of while
    close(tempFd);
    return 0;
}//of main

运行截图

  •  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值