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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/84503591

在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;
}

运行截图如下:

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/84503591