环境:Vmware Workstation;CentOS-6.4-x86_64
说明:
1、write(fd, buf, sizeof(buf));和write(fd, buf, strlen(buf));的区别。
2、write(fd, buf, strlen(buf));向文件中写入内容的是,只会把缓冲区中的有效内容全部拷贝到文件中。
3、write(fd, buf, sizeof(buf));会把缓冲区中的所有数据拷贝到文件中。
使用程序说明:
1、编写源文件main.c:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *args[])
{
// 以只写的方式打开两个文件
int fd1 = open("a.txt", O_WRONLY);
int fd2 = open("b.txt", O_WRONLY);
// 定义写入文件需要缓冲区
char buf[1024];
// 清空缓冲区数据
memset(buf, 0, sizeof(buf));
// 向缓冲区写入数据
strcpy(buf, "hello world");
// 把缓冲区数据写入到文件中
write(fd1, buf, strlen(buf));
write(fd2, buf, sizeof(buf));
// 关闭文件
close(fd1);
close(fd2);
return 0;
}
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]$ touch a.txt 创建文件a.txt
[negivup@negivup mycode]$ touch b.txt 创建文件b.txt
[negivup@negivup mycode]$ make 编译程序
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ ./main 执行程序
[negivup@negivup mycode]$ ls -l 查看文件大小
总用量 28
-rw-rw-r--. 1 negivup negivup 11 9月 19 07:38 a.txt 这个使用的是strlen,文件大小是11,是"hello world"的长度
-rw-rw-r--. 1 negivup negivup 1024 9月 19 07:38 b.txt 这个使用的是sizeof,文件大小是1024,刚好是缓冲区的大小
-rwxrwxr-x. 1 negivup negivup 7282 9月 19 07:38 main
-rw-rw-r--. 1 negivup negivup 1329 9月 19 07:37 main.c
-rw-rw-r--. 1 negivup negivup 2096 9月 19 07:38 main.o
-rw-rw-r--. 1 negivup negivup 235 9月 19 06:56 makefile
说明:
在使用write向文件中写入数据的时候,一般使用write(fd, buf, strlen(buf));
PS:根据传智播客视频学习整理得出。