系统级程序设计(一)

文件操作函数

  • open函数

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

O_RDONLY 只读打开

O_WRONLY 只写打开

O_RDWR 可读可写打开

当我们附带了权限后,打开的文件就只能按照这种权限来操作。

以上这三个常数中应当只指定一 个。下列常数是可选择的:

O_CREAT 若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。

O_EXCL 如果同时指定了OCREAT,而文件已经存在,则出错。

O_APPEND 每次写时都加到文件的尾端。(写文件在文件末尾不会覆盖原先内容)

        O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0。(如果文件里面有东西直接删然后写)

  •  read函数

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

 

Linux read命令用于从标准输入读取数值。

read 内部命令被用来从标准输入读取单行数据。这个命令可以用来读取键盘输入,当使用重定向的时候,可以读取文件中的一行数据。

  • write函数

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

 

  • lseek函数

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

成功返回0,否则返回-1 

案例:

#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";

    tempFd=open(tempFileName,O_RDWR|O_EXCL|O_TRUNC,S_IRWXG);
    if(tempFd==-1){
        perror("file open error.\n");
        exit(-1);
    } //of if

    int tempLen=0;
    char tempBuf[100]={0};
    scanf("%s",tempBuf);
    tempLen=strlen(tempBuf);
    write(tempFd,tempBuf,tempLen);
    close(tempFd);

    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
 

先创建test.txt,然后创建test.c

写入老师给的代码,运行代码

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值