深入Linux文件编程核心,编织数据的经纬,构建高效系统的坚实基石!#Linux系统编程中的文件编程(上)

前言

  本篇博文深入浅出地介绍了Linux系统编程中的文件编程(上),涵盖了一系列基础而关键的内容,包括:文件编程的概述、文件的打开与创建方法、文件的写入操作编程技巧、文件的读取操作详解、文件光标的灵活移动操作、以及open函数的深入补充与creat函数的高效使用。若您对Linux文件编程感兴趣,不妨先点赞收藏,再细细品读。

预备知识

  一、C变量
  二、基本输入输出
  三、流程控制
  四、函数
  五、指针
  六、字符串
  七、Linux系统基本操作命令如mkdir,ls -l等。

  如果以上知识不清楚,请自行学习后再来浏览。如果我有没例出的,请在评论区写一下。谢谢啦!

一、 文件编程概述

1.1 学习方向

  Linux系统编程中的文件操作领域确实既广泛又深入,它全面覆盖了从文件系统的基础架构到具体访问技术的多个维度。这不仅仅涉及文件系统的运作机制,还深入到文件在Linux内核中的高效管理策略,以及核心数据结构如文件信息节点(inode)的深入剖析。此外,文件共享机制与复杂的文件权限系统也是不可或缺的一部分,后者详尽地定义了不同用户(文件所有者、所属群组及其他用户)对文件的访问权限,既确保了系统的安全性,又促进了资源的有效共享与管理。
  对于初学者而言,直接深入Linux系统编程中的文件操作细节可能会感到有些吃力,因此建议采取以实用应用为导向的学习策略。具体而言,可以从处理实际生活中的任务出发,如账单管理、游戏进度保存、配置文件读写等,通过动手实践来逐步掌握文件操作的基本概念和技巧。这种方法不仅能够让学习者快速看到学习成果,还能在实际操作中不断加深和巩固对文件编程的理解。
  在学习Linux文件编程时,核心目标应聚焦于如何通过编写代码来实现对文件的自动化操作。这涵盖了文件的创建、打开、读写(编辑)、以及关闭等一系列关键步骤。一旦掌握了这些基本技能,学习者便能构建出能够自动执行复杂文件处理任务的程序,从而显著提升工作效率和操作的准确性。

1.2 windows手动修改文件

  例如:写word文档

请添加图片描述

1.3 计算机自动化完成修改文件操作

  操作系统提供了一系列的API如Linux系统:
  打开    open
  读写    read/write
  光标定位  seek
  关闭    close

二、 文件打开及创建

2.1 open函数的介绍

SYNOPSIS
       使用open函数需要包含以下头文件
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

       int open(const char *pathname, int flags);
       pathname:文件的路径	flags:打开的权限
       int open(const char *pathname, int flags, mode_t mode);
	   mode_t mode:打开的模式
       int creat(const char *pathname, mode_t mode);

DESCRIPTION
       Given  a  pathname  for  a file, open() returns a file descriptor, a
       small, nonnegative  integer  for  use  in  subsequent  system  calls
       (read(2),  write(2), lseek(2), fcntl(2), etc.).  The file descriptor
       returned by a successful  call  will  be  the  lowest-numbered  file
       descriptor not currently open for the process.
       译:给定一个文件的路径名,open()返回一个文件描述符,一个小的非负
	   整数,用于后续的系统调用(read(2)write(2)lseek(2)fcntl(2))。
       成功调用返回的文件描述符将是当前未为进程打开的编号最低的文件描述符。

参数说明:
	Pathname:要打开的文件名(含路径,缺省为当前路径)
Flags:
    O_RDONLY 只读打开         O_WRONLY 只写打开         O_RDWR  可读可写打开

    当我们附带了权限后,打开的文件就只能按照这种权限来操作。
    以上这三个常数中应当只指定一 个。下列常数是可选择的:     
        O_CREAT 若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。
        O_EXCL 如果同时指定了OCREAT,而文件已经存在,则出错。        
        O_APPEND 每次写时都加到文件的尾端。
        O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0。

Mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限


2.2 文件描述符的介绍

请添加图片描述

2.3 open函数实战编程

2.3.1 程序代码
//使用open函数需要包含以下头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//使用printf函数需要包含以下头文件
#include <stdio.h>

int main()
{
        int fd;                     //定义一个整型文件描述符fd

        fd = open("./file",O_RDWR); //让fd等与open函数返回值
        printf("fd  = %d\n",fd);    //输出fd的值
        if(fd == -1)                //fd = -1 说明打开文件失败
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603); //文件打开失败并创建它,文件权限为0600
        if(fd > 0)                  //fd > 0 说明文件打开成功
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);     //输出fd的值

        return 0;
}
2.3.2程序输出结果
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ ls 
a.out  file  File_programming.c
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ gcc File_programming.c CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ ./a.out 
fd  = 3
open file successful
fd = 4
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ rm file 删除file,使file打开失败
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ ls
a.out  File_programming.c
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ ./a.out 
fd  = -1     说明file打开失败
open file fail
open file successful  说明file创建成功
fd = 3
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$
2.3.3文件权限说明

请添加图片描述

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$ ls -l 列出文件清单
total 16
-rwxr-xr-x 1 CLC book 8490  86 19:19 a.out
-rw------x 1 CLC book    0  86 19:19 file
-rw-r--r-- 1 CLC book  341  86 19:35 File_programming.c
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/01_File_open_creat$

三、 文件写入操作编程

3.1 write函数介绍

NAME
       write - write to a file descriptor

SYNOPSIS
       #include <unistd.h>      使用write函数需要包含此头文件

       ssize_t write(int fd, const void *buf, size_t count);
	   fd:用于写操作的文件描述符
	   buf: 数据缓存区
	   count:数据的大小
DESCRIPTION
       write()  writes up to count bytes from the buffer pointed buf to the
       file referred to by the file descriptor fd.

       The number of bytes written may be less than count if, for  example,
       there  is  insufficient  space on the underlying physical medium, or
       the RLIMIT_FSIZE resource limit is encountered  (see  setrlimit(2)),
       or the call was interrupted by a signal handler after having written
       less than count bytes.  (See also pipe(7).)

       For a seekable file (i.e., one to which lseek(2) may be applied, for
       example,  a  regular  file)  writing takes place at the current file
       offset, and the file offset is incremented by the  number  of  bytes
       actually written.  If the file was open(2)ed with O_APPEND, the file
       offset is first set to the end of  the  file  before  writing.   The
       adjustment  of the file offset and the write operation are performed
       as an atomic step.

       POSIX requires that a read(2) which can be proved to occur  after  a
       write()  has  returned returns the new data.  Note that not all file
       systems are POSIX conforming.

RETURN VALUE
       On success, the number of bytes written is returned (zero  indicates
       nothing  was  written).   On error, -1 is returned, and errno is set
       appropriately.

  译:
  描述
  Write()从指向的缓冲区中最多写入数个字节
  文件描述符fd引用的文件。

  例如,如果底层物理介质上的空间不足,或者遇到RLIMIT_FSIZE资源限制(参见setrlimit(2)),或者在写入少于count字节后被信号处理程序中断,则写入的字节数可能小于count。(参见pipe(7)。)

  对于可寻的文件(例如,可以应用lseek(2)的文件,例如普通文件),写入发生在当前文件偏移量处,并且文件偏移量按实际写入的字节数递增。如果文件是以O_APPEND打开的(2),那么在写入之前,文件偏移量首先设置为文件的末尾。文件偏移量的调整和写入操作作为原子步骤执行。

  POSIX要求可以证明发生在write()返回之后的read(2)返回新数据。请注意,并非所有文件系统都符合POSIX。

  返回值
  如果成功,则返回写入的字节数(0表示没有写入任何内容)。如果出现错误,则返回-1,并适当地设置errno。

3.2 close函数介绍

SYNOPSIS
       #include <unistd.h>  使用close函数需要包含此头文件

       int close(int fd);   要使用该函数关闭文件,您只需将对应文件的文件描述符(fd)作为参数传递给该函数即可。

3.3 write函数编程实战

3.3.1 程序代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>     使用write和close函数需要包含此头文件
#include <string.h>     使用strlen函数吸需要包含此头文件

int main()
{
        int fd;
        定义一个字符缓冲区,里面填入:成功写入字符串的英文
        char *buf = "Successful write string!";  

        fd = open("./file",O_RDWR);
        printf("fd  = %d\n",fd);
        if(fd == -1)
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603);
        if(fd > 0)
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);
        向file中写入缓冲区的字符串
        write(fd,buf,strlen(buf));
        关闭file 
        close(fd);

        return 0;
}
3.3.2 程序运行结果
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/02_File_write$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/02_File_write$ ./a.out 
fd  = 3
open file successful
fd = 4
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/02_File_write$ vi file 打开文件file

文件内容
Successful write string!

四、 文件读取操作

4.1 read函数介绍

NAME
       read - read from a file descriptor

SYNOPSIS
       #include <unistd.h>  使用read函数需要包含此头文件

       ssize_t read(int fd, void *buf, size_t count);
	   fd:用于读操作的文件描述符
	   buf:用于存放读取到的数据缓冲区
	   count:用于读取数组的字节数
DESCRIPTION
       read()  attempts  to  read up to count bytes from file descriptor fd
       into the buffer starting at buf.

       If count is zero, read() returns zero and has no other results.   If
       count is greater than SSIZE_MAX, the result is unspecified.

RETURN VALUE
       On success, the number of bytes read is returned (zero indicates end
       of file), and the file position is advanced by this number.   It  is
       not  an  error  if  this  number is smaller than the number of bytes
       requested; this may happen for example because fewer bytes are actu‐
       ally  available  right  now  (maybe because we were close to end-of-
       file, or because we are reading from a pipe, or from a terminal), or
       because  read()  was  interrupted  by  a  signal.   On  error, -1 is
       returned, and errno is set appropriately.  In this case it  is  left
       unspecified whether the file position (if any) changes.
ERRORS
       EAGAIN The  file  descriptor fd refers to a file other than a socket
              and has been marked nonblocking (O_NONBLOCK),  and  the  read
              would block.

  译:
  描述
  Read()尝试从文件描述符fd读入缓冲区,从buf开始读入字节数。
​  如果count为零,read()返回零并且没有其他结果。如果count大于SSIZE_MAX,则不指定结果。

  返回值
  如果成功,则返回读取的字节数(0表示文件结束),并且文件位置按此数前进。如果此数字小于请求的字节数,则不存在错误;例如,这可能发生,因为现在实际可用的字节较少(可能是因为我们接近文件结束,或者因为我们正在从管道或终端读取),或者因为read()被一个信号中断了。如果出现错误,则返回-1,并适当地设置errno。在这种情况下,不指定文件位置(如果有的话)是否更改。

  错误
  文件描述符fd引用的文件不是套接字,并且被标记为非阻塞(O_NONBLOCK),读取将阻塞。

4.2 read函数编程实战

4.2.1 程序代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>    使用read函数需要包含此头文件
#include <string.h>    
#include <stdlib.h>    使用malloc函数需要包含此头文件

int main()
{
        int fd;
        int n_write;   定义一个整型变量n_write,用于承接write函数已写入的字节数
        int n_read;	   定义一个整型变量n_read,用于承接read函数读取到的字节数
        char *readBuf = NULL;  定义一个用于存放read读取到的数据缓冲区readBuf
        char *buf = "Successful write string!";

        fd = open("./file",O_RDWR);
        printf("fd  = %d\n",fd);
        if(fd == -1)
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603);
        if(fd > 0)
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);
        n_write = write(fd,buf,strlen(buf));  
        printf("n_write = %d\n",n_write);
        readBuf = (char *)malloc(sizeof(char *) * n_write + 1);  给readBuf分配空间
        n_read  = read(fd,readBuf,n_write);  进行读取文件操作
        printf("n_read = %d;readBuf = %s\n",n_read,readBuf); 输出读取到的文件信息。
        close(fd);

        return 0;
}
4.2.2 输出结果
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/03_File_read$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/03_File_read$ ./a.out 
fd  = 3
open file successful
fd = 4
n_write = 24
n_read = 0;readBuf =
4.2.3 输出结果错误的原因

请添加图片描述

4.2.4 采用解决办法2后的程序代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main()
{
        int fd;
        int n_write;
        int n_read;
        char *readBuf = NULL;
        char *buf = "Successful write string!";

        fd = open("./file",O_RDWR);
        printf("fd  = %d\n",fd);
        if(fd == -1)
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603);
        if(fd > 0)
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);
        n_write = write(fd,buf,strlen(buf));
        printf("n_write = %d\n",n_write);
        close(fd);                        先关闭文件
        readBuf = (char *)malloc(sizeof(char *) * n_write + 1);
        fd = open("./file",O_RDWR);       再打开文件
        n_read  = read(fd,readBuf,n_write);
        printf("n_read = %d;readBuf = %s\n",n_read,readBuf);
        close(fd);

        return 0;
}
4.2.5 解决错误后的运行结果
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/03_File_read$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/03_File_read$ ./a.out 
fd  = 3
open file successful
fd = 4
n_write = 24
n_read = 24;readBuf = Successful write string!

五、 文件光标移动操作

5.1 lseek函数介绍

5.1.1 man手册介绍
SYNOPSIS
       使用lseek函数需要包含以下头文件
       #include <sys/types.h>
       #include <unistd.h>

       off_t lseek(int fd, off_t offset, int whence);
	   fd:用于移动操作的文件描述符
	   offset:相对于whence的偏移量
	   whence:固定点位置
DESCRIPTION
       The lseek() function repositions the offset of the open file associ‐
       ated with the file descriptor fd to the argument offset according to
       the directive whence as follows:

       SEEK_SET
              The offset is set to offset bytes.

       SEEK_CUR
              The offset is set to its current location plus offset bytes.

       SEEK_END
              The offset is set to the size of the file plus offset bytes.

RETURN VALUE
       Upon successful completion, lseek()  returns  the  resulting  offset
       location  as  measured  in bytes from the beginning of the file.  On
       error, the value (off_t) -1 is returned and errno is set to indicate
       the error.

  译:
  描述
  lseek()函数将与文件描述符fd相关的打开文件的偏移量重新定位为参数offset,如下所示:

  SEEK_SET
  偏移量设置为偏移字节。

  SEEK_CUR
  偏移量设置为其当前位置加上偏移量字节。

  SEEK_END
  偏移量设置为文件大小加上偏移量字节。

  返回值
  成功完成后,lseek()返回结果偏移位置,以字节为单位从文件开始测量。如果出现错误,则返回值(off_t) -1,并设置errno来指示错误。

5.1.2 lseek函数参数说明

请添加图片描述

5.2 lseek实战编程

5.2.1 whence为SEEK_SET,offset为0

  程序代码:

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

int main()
{
        int fd;
        int n_write;
        int n_read;
        char *readBuf = NULL;
        char *buf = "Successful write string!";
        fd = open("./file",O_RDWR);
        printf("fd  = %d\n",fd);
        if(fd == -1)
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603);
        if(fd > 0)
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);
        n_write = write(fd,buf,strlen(buf));
        printf("n_write = %d\n",n_write);
        lseek(fd,0,SEEK_SET);           移动光标到文件开始位置
        readBuf = (char *)malloc(sizeof(char *) * n_write + 1);
        n_read  = read(fd,readBuf,n_write);
        printf("n_read = %d;readBuf = %s\n",n_read,readBuf);
        close(fd);

        return 0;
}

  运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ ./a.out 
fd  = 3
open file successful
fd = 4
n_write = 24
n_read = 24;readBuf = Successful write string!
5.2.2 whence为SEEK_CUR,offset为-n_write

  程序代码


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

int main()
{
        int fd;
        int n_write;
        int n_read;
        char *readBuf = NULL;
        char *buf = "Successful write string!";

        fd = open("./file",O_RDWR);
        printf("fd  = %d\n",fd);
        if(fd == -1)
        {
                puts("open file fail");
        }
        fd = open("./file",O_RDWR|O_CREAT,0603);
        if(fd > 0)
        {
                puts("open file successful");
        }
        printf("fd = %d\n",fd);
        n_write = write(fd,buf,strlen(buf));
        printf("n_write = %d\n",n_write);
        lseek(fd,-n_write,SEEK_CUR);       移动光标到文件开头
        readBuf = (char *)malloc(sizeof(char *) * n_write + 1);
        n_read  = read(fd,readBuf,n_write);
        printf("n_read = %d;readBuf = %s\n",n_read,readBuf);
        close(fd);

        return 0;
}

  运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ ./a.out 
fd  = 3
open file successful
fd = 4
n_write = 24
n_read = 24;readBuf = Successful write string!
5.2.3 使用lseek函数计算文件大小

  使用ls -l列出文件清单

total 20
-rwxr-xr-x 1 CLC book 8745  87 12:10 a.out
-rw------x 1 CLC book   24  87 12:10 file    file的文件大小为24字节
-rw-r--r-- 1 CLC book  756  87 12:15 File_programming.c

  使用lseek函数计算file的文件大小
  程序代码

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

int main()
{
        int fd;
        int n_lseek;     定义一个整型变量n_lseek承接lseek函数返回值

        fd = open("./file",O_RDWR);
        n_lseek = lseek(fd,0,SEEK_END);   将file文件光标从头移动到尾,并返回偏移量
        printf("n_lseek = %d\n",n_lseek); 输出偏移量,既是文件大小,文件中是英文字符,每个英文字符占1字节

        return 0;
}

  程序运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ gcc File_programming2.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/04_File_cursor_move$ ./a.out 
n_lseek = 24

六、open函数补充及creat函数使用

6.1 O_EXCL使用

6.1.1 O_EXCL介绍

  O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则会打开文件失败,返回-1。常用于判断文件是否存在

6.1.2 O_EXCL编程实战

  程序代码

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

int main()
{
        int fd;
        int n_lseek;

        fd = open("./file",O_RDWR|O_CREAT|O_EXCL); 如果文件存在,打开文件失败,返回-1
        if(fd == -1)
        {
        	printf("file exist!!!\n");
        }
        return 0;
}

  运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ gcc File_programming.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ ./a.out 
file exist!!!

6.2 O_APPEND使用

6.2.1 O_APPEND介绍

  O_APPEND 每次写时都加到文件的尾端。

6.2.2 O_APPEND编程实战

  不加O_APPEND直接向已有内容的文件中写入数据
  文件中的数据为:123456789123456789
  程序代码

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

int main()
{
        int fd;
        int n_lseek;
        char *buf = "Data is successfully written to the file";
        char *readBuf = NULL;

        fd = open("./file",O_RDWR);
        write(fd,buf,strlen(buf));
        lseek(fd,0,SEEK_SET);
        readBuf = (char *)malloc(sizeof(char*) * strlen(buf) + 1);
        read(fd,readBuf,strlen(buf));
        printf("readBuf = %s\n",readBuf);
        close(fd);

        return 0;
}

  程序运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ gcc File_programming2.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ ./a.out 
readBuf = Data is successfully written to the file		说明文件已被覆盖

  使用O_APPEND
  文件中的数据为:123456789123456789
  程序代码

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

int main()
{
        int fd;
        int n_lseek;
        char *buf = "Data is successfully written to the file";
        char *readBuf = NULL;

        fd = open("./file",O_RDWR|O_APPEND);
        write(fd,buf,strlen(buf));
        lseek(fd,0,SEEK_SET);
        readBuf = (char *)malloc(sizeof(char*) * strlen(buf) + 19);  
        read(fd,readBuf,strlen(buf)+19);19的原因是为了将原有的数据读出来。
        printf("readBuf = %s\n",readBuf);
        close(fd);

        return 0;
}

  程序运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ gcc File_programming3.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ ./a.out 
readBuf = 123456789123456789
Data is successfully written to the file 写入的数据成功加到文件末端

6.3 O_TRUNC使用

6.3.1 O_TRUNC介绍

  O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0。意思是将文件中原有的数据抹除,写入新数据

6.3.2 O_TRUNC编程实战

  文件中的数据为:123456789123456789
  程序代码

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

int main()
{
        int fd;
        int n_lseek;
        char *buf = "Data is successfully written to the file";
        char *readBuf = NULL;

        fd = open("./file",O_RDWR| O_TRUNC);  这里已使用
        write(fd,buf,strlen(buf));
        lseek(fd,0,SEEK_SET);
        readBuf = (char *)malloc(sizeof(char*) * strlen(buf) + 1);
        read(fd,readBuf,strlen(buf)+1);
        printf("readBuf = %s\n",readBuf);
        close(fd);
        return 0;
}

  程序运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ gcc File_programming4.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ ./a.out 
readBuf = Data is successfully written to the file		说明file内容已被覆盖

6.4 creat函数使用

6.4.1 creat函数介绍

  man手册介绍参见2.1
  补充介绍

在这里插入图片描述

6.4.2 creat函数编程实战

  程序代码

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

int main()
{
        int fd;
        int n_lseek;
        char *buf = "Data is successfully written to the file";
        char *readBuf = NULL;

        fd = creat("./file2",S_IRWXU);     创建一个可读可写可执行文件file2
        printf("fd =%d\n",fd);
        write(fd,buf,strlen(buf));
        fd = open("./file2",O_RDWR);       这里我想用移动光标到文件前端,但是这样却无法读取,可能是此时用户没有读的权限对file2操作,所以我直接打开。
        readBuf = (char *)malloc(sizeof(char*) * strlen(buf) + 1);
        read(fd,readBuf,strlen(buf)+1);
        printf("readBuf = %s\n",readBuf);
        close(fd);

        return 0;
}

  运行结果

CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ gcc File_programming5.c 
CLC@Embed_Learn:~/Linux_System_Programming/Linux_file_programming/05_Open_Creat$ ./a.out 
fd =3
readBuf = Data is successfully written to the file

结束语

  很高兴您能看到这里,点个赞再走呗。谢谢您啦!!!

  • 23
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值