create()和open()

9 6 月, 2010 by edsionte Leave a reply »

creat()和open()都可以创建文件,但是稍有区别。如果按照如下方式设置参数则两者是等价的:

open(const char* pathname, (O_CREAT|O_WRONLY|O_TRUNC),mode_t mode);
creat(const char* pathname,mode_t mode);

若要创建的文件不存在,则按照mode方式创建新文件。当要创建的文件已经存在到时候,覆盖原有文件。事实上是因为O_WRONLY|O_TRUNC参数的原因:当文件存在并且以可写方式打开的时候,原有文件到长度则清0,即会清空原有文件,但是文件属性不变,与原有文件方式相同,并不会设置成mode方式。

在下面的源代码中,以open函数方式创建文件时,由于设置拉O_CREAT|O_EXCL参数,当要创建到文件不存在时,open函数创建这个文件,并且文件到存取权限为S_IRUSR|S_IWUSR。当文件存在时因为设置拉O_EXCL则出现错误。而当以creat()方式创建文件时,如本文开头所述,无论是否存在将要创建的那个文件,都不会出现错误。

下面作测试。

首先注意,在下面的源代码中open()函数中的文件权限s设置为:S_IRUSR|S_IWUSR(文件所有着可读可写)。creat()设置的文件权限为:S_IRWXU(文件所有者可读可写可执行)。

第一次运行本程序,选择使用open()创建example_62.c。

please select a way of creating files:
1.creat 2.open
2
create file success
edsionte@edsionte-laptop:~/code$ ls -l
总用量 48
-rw------- 1 edsionte edsionte    0 2010-06-16 12:38 example_62.c

第二次运行本程序,以creat()创建文件,依然会运行成功,但是此时的example_62.c的存取权限是否是creat()中设置的S_IRWXU呢?

edsionte@edsionte-laptop:~/code$ ./my_create
please select a way of creating files:
1.creat 2.open
1
create file success
edsionte@edsionte-laptop:~/code$ ls -l
总用量 48
-rw------- 1 edsionte edsionte    0 2010-06-16 12:40 example_62.c

正如上面所述的,creat()创建已存在的文件,并不会更改原文件的属性。

源代码如下:

#include "stdio.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "unistd.h"
#include "error.h"

int main()
{
	int fd,n;
	printf("please select a way of creating files:\n");
	printf("1.creat 2.open\n");
	scanf("%d",&n);
	if(n==1)
	{
		if((fd=creat("example_62.c",S_IRWXU))==-1)
		{
			perror("open");
			exit(1);
		}
		else
		{
			printf("create file success\n");
		}
	}
	else if(n==2)
	{
		if((fd=open("example_62.c",O_CREAT|O_EXCL,S_IRUSR|S_IWUSR))==-1)
		{
			perror("open");
			exit(1);
		}
		else
		{
			printf("create file success\n");
		}
	}
	else
	{
		printf("your choice may be wrong\n");
	}
	close(fd);
	return 0;
}

create()和open()是文件操作中最基本的函数,大家应该在实践中不断总结。

Advertisement

发表回复

windows 7 ultimate product key

windows 7 ultimate product key

winrar download free

winrar download free

winzip registration code

winzip registration code

winzip free download

winzip free download

winzip activation code

winzip activation code

windows 7 key generator

windows 7 key generator

winzip freeware

winzip freeware

winzip free download full version

winzip free download full version

free winrar download

free winrar download

free winrar

free winrar

windows 7 crack

windows 7 crack

windows xp product key

windows xp product key

windows 7 activation crack

windows7 activation crack

free winzip

free winzip

winrar free download

winrar free download

winrar free

winrar free

download winrar free

download winrar free

windows 7 product key

windows 7 product key