zoukankan      html  css  js  c++  java
  • [基础|理论|实验]linux下的文件读写

    1.在Linux平台下对文件编程可以使用两类函数:(1)Linux操作系统文件API;(2)C语言I/O库函数。 前者依赖于Linux系统调用,后者实际上与操作系统是独立的,因为在任何操作系统下,使用C语言I/O库函数操作文件的方法都是相同的。

    2.Linux文件API主要常用的有open,write,read,close,lseek,ioctl这几个函数。

     主要包含头文件有:

    1 #include <unistd.h>
    2 #include <fcntl.h>

     实例:

    编写一个程序,在当前目录下创建用户可读写文件“hello.txt”,在其中写入“Hello, software weekly”,关闭该文件。再次打开该文件,读取其中的内容并输出在屏幕上。
     1   #include <unistd.h>
     2   #include <fcntl.h>
     3   #include <stdio.h>
     4  
     5   #define LENGTH 100
     6   main()
     7   {
     8    int fd, len;
     9    char str[LENGTH];
    10   fd = open("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); /* 创建并打开文件 */
    11  if (fd)
    12   {
    13    write(fd, "Hello, Software Weekly"sizeof("Hello, software weekly")-1); /* 写入 Hello, software weekly字符串,这里长度-1是因为sizeof把整个常量的所有大小,包括了\0,可以参考基础理论sizeof与strlen的区别,write与read不将\0代入缓冲区,*/
    14    close(fd);
    15   }
    16   fd = open("hello.txt", O_RDWR);
    17   len = read(fd, str, LENGTH); /* 读取文件内容 */
    18   printf("%s\n", str);
    19   close(fd);
    20  }
     
    作者:xiaoxia

    出处:http://cnblogs.com/xiaoxia

    本文遵从GNU 的自由文档许可证(Free Document License)的条款,欢迎转载、修改、散布。 

  • 相关阅读:
    什么是webview
    juqery.fn.extend和jquery.extend
    LeetCode
    5. Longest Palindromic Substring
    42. Trapping Rain Water
    11. Container With Most Water
    621. Task Scheduler
    49. Group Anagrams
    739. Daily Temperatures
    3. Longest Substring Without Repeating Characters
  • 原文地址:https://www.cnblogs.com/xiaoxia/p/2095455.html
Copyright © 2011-2022 走看看