Linux学习笔记-Linux下读写文件

134 篇文章 10 订阅

在Linux编程需要读写文件时,有两种方式:
(1)ANSIC: 使用stdio.h里的函数。fopen, fclose, fwrite, fread
(2)Linux API:Linux提供了另外一套API用于操作文件。open, close,  write,  read

ANSI C优点:被各平台都支持,因此一份代码可以适用多种平台。

 

ANSIC函数:
(1)文件路径: 使用/
(2)文本文件时,换行符有区别
windows: \r\n
linux: \n
注:换行符是一个约定俗成的东西

 

Linux API文件操作
以下三者选一:
O_RDONLY 只读方式
O_WRONLY 以只写方式打开文件
O_RDWR 以可读写方式打开文件
额外的标识位:
O_CREAT可与O_WRONLY联用,若欲打开的文件不存在则自
动建立该文件
O_TRUNC  可与O_WRONLY联用,在打开文件时清空文件
O_APPEND可与O_WRONLY联用,表示追加内容
O_NONBLOCK 表示以“非阻塞”方式读/写数据时

 

过程如下:

当前文件和路径如下:

 

使用ANSIC函数

#include <stdio.h>
#include <string.h>

int main(){

        FILE *fp = fopen("/root/CDemo/CFile/a.txt", "wb");
        if(!fp){
                printf("open failed!\n");
                return -1;
        }

        char buf[] = "hello\nworld\n";
        fwrite(buf, 1, strlen(buf), fp);
        fclose(fp);
        return 0;
}

运行截图如下:

 

使用Linux API

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){

        int fd = open("/root/CDemo/CFile/b.txt", O_WRONLY | O_CREAT, 0644);

        if(fd < 0){

                printf("open failed!\n");
                return -1;
        }

        char data[12] = "Linux";
        write(fd, data, 5);
        close(fd);
        return 0;
}

 

读取文件:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){

        int fd = open("/root/CDemo/CFile/a.txt", O_RDONLY);

        if(fd < 0){
                printf("open failed!\n");
                return -1;
        }

        char data[128];
        int n = read(fd, data, 128);
        if(n > 0){
                data[n] = 0;
                printf("read:%s \n", data);
        }
        close(fd);

        return 0;
}

运行截图如下:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值