• Linux C 文件与目录3 文件读写


    文件读写

      文件读写是指从文件中读出信息或将信息写入到文件中。Linux文件读取可使用read函数来实现的,文件写入可使用write函数来实现。在进行文件写入的操作时,只是在文件的缓冲区中操作,可能没有立即写入到文件中。需要使用sync或fsync函数将缓冲区的数据写入到文件中


     

    文件写操作:

    函数write可以把一个字符串写入到一个已经打开的文件中,这个函数的使用方法如下:

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

    参数:

      fd:已经打开文件的文件编号。

      buf:需要写入的字符串。

      count:一个整数型,需要写入的字符个数。表示需要写入内容的字节的数目。

    返回值:

      如果写入成功,write函数会返回实际写入的字节数。发生错误时则返回-1,可以用errno来捕获发生的错误。

    [Linux@centos-64-min exercise]$ cat write.c
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <string.h>
    #include <errno.h>
    int main(void)
    {
    int fd ;
    char path[] = "txt1.txt";
    char s[]="hello ...";
    extern int errno;
    fd = open(path , O_WRONLY|O_CREAT|O_TRUNC , 0766);
    if(fd != -1)
    {
    printf("opened file %s . " , path);
    }
    else
    {
    printf("can't open file %s. " , path);                          
    printf("errno: %d " , errno);                          //打印错误编号
    printf("ERR : %s " , strerror(errno));             //打印错误编号对应的信息。
    }
    write(fd , s , sizeof(s));
    close(fd);
    printf("Done ");
    return 0;
    }

    [Linux@centos-64-min exercise]$ ./write
    opened file txt1.txt .
    Done


    读取文件函数read

    函数read可以从一个打开的文件中读取字符串。

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

    参数:fd:表示已经打开的文件的编号。

       buf:是个空指针,读取的内容会返回到这个指针指向的字符串。

       count:表示需要读取的字符的个数。

    返回值:返回读取到字符的个数。如果返回值为0,表示已经达到文件末尾或文件中没有内容可读。

    fd = open(path , O_RDONLY);
    if(fd != -1)
    {
    printf("opened file %s . " , path);
    }
    else
    {
    printf("can't open file %s. " , path);
    printf("errno: %d " , errno);
    printf("ERR : %s " , strerror(errno));
    }
    if((size = read(fd , str , sizeof(str))) < 0)
    {
    printf("ERR: %s" , strerror(size));                    //如果有错,通过错误编号打印错误消息。
    }
    else
    {
    printf("%s " , str);
    printf("%d " , size);
    }
    close(fd);
    return 0;
    }

    result:

      

    opened file txt1.txt .
    hello ...
    10

  • 相关阅读:
    POJ 3687 Labeling Balls()
    POJ 2777 Count Color(线段树之成段更新)
    POJ 1961 Period( KMP )*
    POJ 2406 Power Strings (KMP)
    hdu 2199 Can you solve this equation?(二分搜索)
    10679 多少个1
    POJ 2823 Sliding Window
    POJ 2299 Ultra-QuickSort(线段树入门)
    最短路径—Dijkstra算法和Floyd算法
    poj1125&zoj1082Stockbroker Grapevine(Floyd算法)
  • 原文地址:https://www.cnblogs.com/King-Penguin/p/5256895.html
Copyright © 2020-2023  润新知