1. 程式人生 > >系統程式設計——read()函式

系統程式設計——read()函式

1、程式檔案

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define SIZE 1024

int main1()
{
	int fd = open("test.c", O_RDONLY);
	
	if (-1 == fd)
	{
		perror("開啟test.c檔案失敗");
		
		return -1;
	}
	
	char buf[11];
	
	// ssize_t read(int fd, void *buf, size_t count);
	// fa:檔案描述符
	// buf:用於臨時存放讀到的資料
	// 10:欲讀取得位元組數
	// ret:實際讀到得位元組數、型別為長整型
	
	// read()會把引數fd所指的檔案傳送nbyte個位元組到buf指標所指的記憶體中。
	// 若引數nbyte為0,則read()不會有作用並返回0。返回值為實際讀取到的位元組數,
	// 如果返回0,表示已到達檔案尾或無可讀取的資料。錯誤返回-1,並將根據不同的錯誤原因適當的設定錯誤碼。
	// ssize_t read(int fd, void *buf, size_t count);
	ssize_t ret = read(fd, buf, 10);
	
	if (-1 == ret)
	{
		perror("讀失敗");
		
		return -1;
	}
	
	printf ("讀到的位元組數:%ld, 讀到的內容:%s\n", ret, buf);
	
	// 成功返回0,出錯返回-1並設定errno引數,fd是要關閉的檔案描述符。需要說明的是,
	// 當一個程序終止時,核心對該程序所有尚未關閉的檔案描述符呼叫close關閉,
	// 所以即使使用者程式不呼叫close,在終止時核心也會自動關閉它開啟的所有檔案
	close(fd);
	
	return 0;
}

int main2()
{
	int fd = open("test.c", O_RDONLY);
	if (-1 == fd)
	{
		perror("開啟test.c檔案失敗");
		return -1;
	}
	
	char buf[SIZE+1];
	int count = 0;
	int ret = 0;
	while ((ret = read(fd, buf, SIZE)) != 0)
	{
		if (-1 == ret)
		{
			perror("讀失敗");
			return -1;
		}
		
		count++;
		buf[ret] = '\0';
		printf ("%s", buf);
	}
	
	printf ("檔案讀結束, 讀了 %d 次\n", count);	
	
	close(fd);
	return 0;
}


// 讀一個完整的大資料
int main()
{
	int fd = open("test.c", O_RDONLY);
	if (-1 == fd)
	{
		perror("開啟test.c檔案失敗");
		return -1;
	}
	
	char buf[SIZE+1];
	char *p = buf;
	
	int count = SIZE;
	while (count)
	{
		int ret = read(fd, p, count);
		if (-1 == ret)
		{
			perror("讀取資料失敗");
			return -1;
		}
		
		printf ("ret = %d\n", ret);
		count -= ret;
		p += ret;
	}
	
	buf[SIZE] = 0;
	printf ("%s",buf);
	close(fd);
	return 0;
}