Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C语言如何清空一个文件的例子

/*********************************************************************
 * Author  : Samson
 * Date    : 02/12/2015
 * Test platform:
 *              3.13.0-24-generic
 *              GNU bash, 4.3.11(1)-release
 * *******************************************************************/
如何使用C语言使一个文件的内容直接就清空了呢?答案就在如下的程序代码中:#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>#define PATHNAME "./test"
int main()
{
        int ret = open(PATHNAME, O_WRONLY | O_TRUNC);
        if(ret == -1)
        {
                printf("open file is fail! ");
                return -1;
        }
        close(ret);
        return 0;
}在当前目录下有一个文件名为test的文件,使用ll命令查看一下文件的大小:linuxidc@linuxidc:/tmp$ ll test-rw-r--r-- 1 linuxidc linuxidc 293  2月 12 17:05 test
linuxidc@linuxidc:/tmp$ gcc testwrite.clinuxidc@linuxidc:/tmp$ ./a.out执行后再查看test文件的大小,即已经为0了,使用cat test也是没有内容显示的了。linuxidc@linuxidc:/tmp$ ll test
-rw-r--r-- 1 linuxidc linuxidc 0  2月 12 17:05 test关键在于open函数中的oflag参数,使用man 2 open可以查看到open函数的说明,O_WRONLY:表示以只写打开文件O_TRUNC:表示如果open中的参数文件名为pathname的文件存在的话,且为只写或读写成功打开的话,则将其长度截智短为0。也就达到了清空文件内容的目的了。C++ 隐式类类型转化 Implicit Class-Type Conversions http://www.linuxidc.com/Linux/2013-01/78071.htmC语言变长数组之剖析 http://www.linuxidc.com/Linux/2013-07/86997.htmC语言需要注意的问题 http://www.linuxidc.com/Linux/2013-05/84301.htmC语言位域的使用及其注意点 http://www.linuxidc.com/Linux/2013-07/87027.htmC语言中简单的for循环和浮点型变量 http://www.linuxidc.com/Linux/2013-08/88514.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-02/113321.htm