设为首页 加入收藏

TOP

Linux系统编程:简单文件IO操作(二)
2018-01-01 06:07:11 】 浏览:865
Tags:Linux 系统 编程 简单 文件 操作
nbsp;   }


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


    //关闭文件
    close( fd );


    return 0;
}


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; //文件描述符


    //打开文件
    //在O_RDWR模式下,对于一个已经存在的文件,且有内容,那么写入文件会覆盖对应大小的源文件内容【不是完全覆盖】
    // fd = open( "ghostwu.txt", O_RDWR );
    //在具有写入权限的文件中,使用O_TRUNC 会先把原来的内容清除,再写入新的内容
    // fd = open( "ghostwu.txt", O_RDWR | O_TRUNC );
    //在具有写入权限的文件中,使用O_APPEND 会把新内容追加到原来内容的后面
    // fd = open( "ghostwu.txt", O_RDWR | O_APPEND );


    //在具有写入权限的文件中,使用O_APPEND和O_TRUNC O_TRUNC起作用,会把原来的内容清除,再写入新的内容
    fd = open( "ghostwu.txt", O_RDWR | O_APPEND | O_TRUNC );


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


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


    //关闭文件
    close( fd );


    return 0;
}


3,文件存在已否,创建文件与设置权限


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


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


    int fd = -1;


    // fd = open( "ghostwu.txt", O_RDWR | O_CREAT | O_EXCL );


    /*
        文件不存在:
            创建这个文件 并打开成功
        文件存在:
            再次运行时(文件已经创建成功,存在了), 这时打开失败
    */
    // fd = open( "ghostwu.txt", O_RDWR | O_CREAT );


    fd = open( "ghostwu.txt", O_RDWR | O_CREAT | O_EXCL, 666 );


    if( -1 == fd ) {
        printf("文件打开失败,错误号:%d\n", errno );
        perror( "open" );
        return -1;
    }else {
        printf("文件打开成功\n");
    }


    close( fd );


    return 0;
}


上面用到了一个函数perror,errno和perror:


1)errno就是error number,意思就是错误号码。linux系统中对各种常见错误做了个编号,当函数执行错误时,函数会返回一个特定的errno编号来告诉我们这个函数到底哪里错了


2)errno是由操作系统来维护的一个全局变量,操作系统内部函数都可以通过设置errno来告诉上层调用者究竟刚才发生了一个什么错误


3)errno本身实质是一个int类型的数字,每个数字编号对应一种错误。当我们只看errno时只能得到一个错误编号数字,并不知道具体错在哪里,所以:linux系统提供了一个函数perror(意思print error),perror函数内部会读取errno并且将这个不好认的数字直接给转成对应的错误信息字符串,然后打印出来


4,lseek用来移动文件内部指针


简单应用:统计文件大小


#include &l

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目