Linux系统函数write(strlen、sizeof与write结合使用的区别)

环境: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:根据传智播客视频学习整理得出。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值