天天看點

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 [email protected] -c $<

clean:
	rm -rf $(EXEC) $(OBJS)           

3、編譯并執行程式,檢視檔案的大小:

[[email protected] mycode]$ touch a.txt                  建立檔案a.txt
[[email protected] mycode]$ touch b.txt                  建立檔案b.txt
[[email protected] mycode]$ make                         編譯程式
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[[email protected] mycode]$ ./main                       執行程式
[[email protected] 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:根據傳智播客視訊學習整理得出。

繼續閱讀