1、creat函数
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.
2、open函数
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