环境:Vmware Workstation;CentOS-6.4-x86_64
说明:
参数和返回值和read函数相同,具体参照《Linux系统函数read说明》。
程序:
实现创建文件,并向文件中写入内容。
步骤:
1、创建并编写源文件main.c:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *args[])
{
// 定义一个参数作为函数的返回值
int return_value = 0;
// 判断用户传递的参数是否符合要求:main 文件名
if (argc < 2)
{
// 输出提示信息
printf("Message : Please input more arguments.\n");
return_value = -1;
return return_value;
}
// 以只写方式打开文件,如果没有文件就创建
// 注意:此处的“|”是位运算符
int fd = open(args[1], O_WRONLY | O_CREAT);
// 没有创建成功,输出提示信息
if (fd == -1)
{
printf("Message : %s\n", strerror(errno));
return_value = -1;
return return_value;
}
// 定义写入文件需要缓冲区
char buf[1024];
// 清空缓冲区数据
memset(buf, 0, sizeof(buf));
// 向缓冲区写入数据
strcpy(buf, "hello world");
// 把缓冲区数据写入到文件中
write(fd, buf, strlen(buf));
// 关闭文件
close(fd);
return return_value;
}
2、创建并编写文件makefile:
.SUFFIXES:.c .o
CC=gcc
SRCS=main.c
OBJS=$(SRCS:.c=.o)
EXEC=main
start: $(OBJS)
$(CC) -o $(EXEC) $(OBJS)
@echo "-----------------------------OK-----------------------"
.c.o:
$(CC) -Wall -o $@ -c $<
clean:
rm -rf $(EXEC) $(OBJS)
3、编译并运行程序:
[negivup@negivup mycode]$ make 这里编译程序
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ main a.txt 这里执行程序
[negivup@negivup mycode]$ ls -l 这里查看文件的权限
总用量 24
-r-x-----T. 1 negivup negivup 11 9月 19 07:20 a.txt
-rwxrwxr-x. 1 negivup negivup 7892 9月 19 07:20 main
-rw-rw-r--. 1 negivup negivup 1716 9月 19 07:20 main.c
-rw-rw-r--. 1 negivup negivup 2344 9月 19 07:20 main.o
-rw-rw-r--. 1 negivup negivup 235 9月 19 06:56 makefile
[negivup@negivup mycode]$ chmod 777 a.txt 修改文件的权限
[negivup@negivup mycode]$ cat a.txt 查看文件的内容
hello world[negivup@negivup mycode]$ ls -l 查看文件的权限
总用量 24
-rwxrwxrwx. 1 negivup negivup 11 9月 19 07:20 a.txt
-rwxrwxr-x. 1 negivup negivup 7892 9月 19 07:20 main
-rw-rw-r--. 1 negivup negivup 1716 9月 19 07:20 main.c
-rw-rw-r--. 1 negivup negivup 2344 9月 19 07:20 main.o
-rw-rw-r--. 1 negivup negivup 235 9月 19 06:56 makefile
程序说明:
1、write函数可以向文件中写入数据。
2、创建完成的文件权限不够,在程序外部不能操作。
PS:根据传智播客视频学习整理得出。