设为首页 加入收藏

TOP

Linux系统编程:简单文件IO操作(一)
2018-01-01 06:07:11 】 浏览:855
Tags:Linux 系统 编程 简单 文件 操作

使用Linux的文件API,经常看见一个东西,叫做文件描述符。


什么是文件描述符?


(1)文件描述符其实实质是一个数字,这个数字在一个进程中表示一个特定的含义,当我们open打开一个文件时,操作系统在内存中构建了一些数据结构来表示这个动态文件,然后返回给应用程序一个数字作为文件描述符,这个数字就和我们内存中维护这个动态文件的这些数据结构挂钩绑定上了,以后我们应用程序如果要操作这一个动态文件,只需要用这个文件描述符进行区分。


(2)文件描述符就是用来区分一个程序打开的多个文件的。


(3)文件描述符的作用域就是当前进程,出了当前进程这个文件描述符就没有意义了


(4)文件描述符fd的合法范围是0或者一个正数,不可能是一个负数


(5)open返回的fd必须记录好,以后向这个文件的所有操作都要靠这个fd去对应这个文件,最后关闭文件时也需要fd去指定关闭这个文件。如果在我们关闭文件前fd丢了,那么这个文件就没法关闭了也没法读写了


1)打开与读取文件


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


int main(int argc, char const *argv[]) {


    int fd = -1; //文件描述符


    //打开文件
    fd = open( "ghostwu.txt", O_RDWR );


    if ( -1 == fd ) {
        printf("文件打开失败\n");
    }else {
        printf("文件打开成功,fd=%d\n", fd );
    }


    //读取文件
    int count = 0;
    char buf[20];
    count = read( fd, buf, 50 );
    if ( -1 == count ) {
        printf("文件读取失败\n");
    }else {
        printf("文件读取成功,实际读取的字节数目为:%d\n内容为%s\n", count, buf );
    }


    //关闭文件
    close( fd );


    return 0;
}


需要在当前目录下存在ghostwu.txt这个文件,否则打开的时候失败,这里涉及2个api


int open(const char *pathname, int flags);


open非常简单,第一个参数就是文件路径, 第二个是文件模式,在man手册中还提供了其他几种方式。


ssize_t read(int fd, void *buf, size_t count);


第一个参数为文件描述符,就是open返回的那个值


第二个参数buf用来存储从文件中读取的内容


第三个参数,表示希望从文件中读取的内容( 注:这个count数字可以随便给,最终以返回的实际数目(read的返回值)为准


2)打开与写入文件


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


int main(int argc, char const *argv[]) {


    int fd = -1; //文件描述符


    //打开文件
    fd = open( "ghostwu.txt", O_RDWR );


    if ( -1 == fd ) {
        printf("文件打开失败\n");
    }else {
        printf("文件打开成功,fd=%d\n", fd );
    }


    //写文件
    char buf[] = "I love Linux, Linux is very very good!!!";
    int count = 0;
    count = write( fd, buf, strlen( buf ) );
    if ( -1 == count ) {
        printf("文件写入失败\n");
    }else {
        printf("文件写入成功,实际写入的字节数目为:%d\n", count);
    }


    //关闭文件
    close( fd );


    return 0;
}


ssize_t write(int fd, const void *buf, size_t count);


第一个参数为文件描述符,就是open返回的那个值


第二个参数buf用来存储写入的内容


第三个参数,表示希望写入的文件大小


3)open的一些flag参数


1,只读与只写权限


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


int main(int argc, char const *argv[]) {


    int fd = -1; //文件描述符


    //打开文件, O_RDONLY:只读权限,打开之后的文件只能读取,不能写入
    //打开文件, O_WRONLY:只写权限,打开之后的文件只能写入,不能读取
    // fd = open( "ghostwu.txt", O_RDONLY );
    fd = open( "ghostwu.txt", O_WRONLY );


    if ( -1 == fd ) {
        printf("文件打开失败\n");
    }else {
        printf("文件打开成功,fd=%d\n", fd );
&

首页 上一页 1 2 3 4 5 下一页 尾页 1/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇多线程CountDownLatch和Join 下一篇ActiveMQ入门案例-生产者代码实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目