设为首页 加入收藏

TOP

Linux系统编程:简单文件IO操作(四)
2018-01-01 06:07:11 】 浏览:871
Tags:Linux 系统 编程 简单 文件 操作
t;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[]) {


    if ( argc != 2 ) {
        printf("usage:%s %s\n", argv[0], "filename");
        return -1;
    }


    int fd = -1;


    fd = open( argv[1], O_RDWR );


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


    //把指针移动到文件末尾,就是文件的大小
    int count = lseek( fd, 0, SEEK_END );


    printf("文件大小为%d\n", count);


    close( fd );
    return 0;
}


------------------------------------------分割线------------------------------------------


一、同一个进程,多次打开同一个文件,然后读出内容的结果是: 分别读【我们使用open两次打开同一个文件时,fd1和fd2所对应的文件指针是不同的2个独立的指针】


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


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


    int fd1 = -1;
    int fd2 = -1;
    char buf1[20] = {0};
    char buf2[20] = {0};
    int count1 = 0;
    int count2 = 0;


    fd1 = open( "ghostwu.txt", O_RDWR );


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


    count1 = read( fd1, buf1, 5 );
    if ( -1 == count1 ) {
        printf( "文件读取失败\n" );
        perror( "read" );
    }else {
        printf( "文件读取成功,读取的内容是%s\n", buf1 );
    }


    fd2 = open( "ghostwu.txt", O_RDWR );


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


    count2 = read( fd2, buf2, 10 );
    if ( -1 == count2 ) {
        printf( "文件读取失败\n" );
        perror( "read" );
    }else {
        printf( "文件读取成功,读取的内容是%s\n", buf2 );
    }


    close( fd1 );
    close( fd2 );


    return 0;
}


二、同一个进程,多次打开同一个文件,然后写入内容的结果是: 分别写,当使用O_APPEND,就是接着写


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


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


    int fd1 = -1;
    int fd2 = -1;
    char buf1[] = "ghost";
    char buf2[] = "wu";
    int count1 = 0;
    int count2 = 0;


    fd1 = open( "ghostwu.txt", O_RDWR );


    if (

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目