歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言如何清空一個文件的例子

C語言如何清空一個文件的例子

日期:2017/3/1 9:33:26   编辑:Linux編程

/*********************************************************************
* 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!\n");
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.c

linuxidc@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.htm

C語言變長數組之剖析 http://www.linuxidc.com/Linux/2013-07/86997.htm

C語言需要注意的問題 http://www.linuxidc.com/Linux/2013-05/84301.htm

C語言位域的使用及其注意點 http://www.linuxidc.com/Linux/2013-07/87027.htm

C語言中簡單的for循環和浮點型變量 http://www.linuxidc.com/Linux/2013-08/88514.htm

Copyright © Linux教程網 All Rights Reserved