【文件】不带缓存的文件I/O操作函数之creat、open

1creat函数

    creat函数用于建立文件。


函数的作用:创建一个文件

函数的原型:

int creat(const char *pathname, mode_t mode);


头文件:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

返回值:

    成功:返回新的文件描述符

    失败:返回-1

示例:

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void creat_file(char *filename)
{
    int num = creat(filename,0755);

    if(num < 0)
    {
        printf("creat file %s failed.\nreturn %d.\n",filename,num);
        exit(EXIT_FAILURE);
    }
    else
    {
        printf("creat file %s success.\nreturn %d.\n",filename,num);
    }
}

int main(int argc, char *argv[])
{
    int i;

    if(argc < 2)
    {
        printf("Error!\nPlease input filename!\n");
        exit(EXIT_FAILURE);
    }

    for(i = 1; i < argc; i++)
    {
        creat_file(argv[i]);
    }

    exit(EXIT_SUCCESS);
}

程序运行结果:

[root@localhost 1015]# ./creat_file 
Error!
Please input filename!

[root@localhost 1015]# ./creat_file hello.c hello1.c hello2.c
creat file hello.c success.
return 3.
creat file hello1.c success.
return 4.
creat file hello2.c success.
return 5.

 

2open函数

    open函数用于打开文件。


函数的作用:打开一个文件

函数的原型:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

头文件:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

返回值:

    成功:返回文件描述符

    失败:返回-1

示例:

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd;

    fd = open("./hello.c",O_RDONLY | O_WRONLY);                    //打开当前目录下的hello.c

    if(fd < 0)
    {
        printf("open is error!\n");
    }
    else
    {
        printf("the open file fd is %d.\n",fd);
    }

    close(fd);

    return 0;
}

程序运行结果:

the open file fd is 3.

程序运行前:

[root@localhost 1015]# ls
creat_file  creat_file.c

程序运行后:

[root@localhost 1015]# ls
creat_file  creat_file.c  hello.c

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值