Linux编程基础2.1:Linux文件系统与操作学后心得

本文详细介绍了Linux编程中关于文件I/O的基本函数,包括open()、read()、write()、lseek()和close(),并提供了案例分析,帮助理解如何在Linux环境下进行文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

  • 有关文件I/O的函数
  • 案列分析


前言

本篇文章主要记录了昨日上课的一些内容:有关文件i/o的函数和有关案列分析


提示:以下是本篇文章正文内容,下面案例可供参考

一、文件I/O

1.1 open函数

open()

打开文件

定义函数: 
 

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

pathname:待打开文件的文件路径名;

flags:访问模式;

返回描述:

调用成功,返回一个文件描述符

不成功,返回-1

1.2 read函数

read()

读取文件

定义函数:

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

fd: 从open或create函数返回的文件描述符

buf: 缓冲区

count: 读取数据的字节数

返回描述:

ssize_t: 有符号的size_t,有三种返回值
– 正数:请求读取的字节数
– 0: 文件长度有限,若读写位置距文件末尾只有20字节,该函数请求读取30字节,则第一次读取时返回值为20,第二次读取时,返回0
– -1: 读取文件出错

1.3 write函数

 write()

写入文件

定义函数:

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

参数同read函数

返回描述:

返回写入的字节数或者-1并设置errno

1.4 lseek函数

lseek()

定义函数:

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

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

成功:返回新的偏移量

不成功:-1

1.5 close函数

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

输出示例:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值