1. 程式人生 > >系統程式設計之檔案系統程式設計

系統程式設計之檔案系統程式設計

系統呼叫:所有的作業系統都提供多種服務的入口點,程式由此向核心請求服務。這些可直接進入核心的入口點被稱為系統呼叫。

不同作業系統提供了自己的一套系統呼叫,所以系統呼叫無法實現跨平臺使用。而且頻繁地系統呼叫,在使用者態和核心態之間切換,很耗費資源,效率不高。C標準庫提供了操作檔案的標準I/O函式庫,與系統呼叫相比,主要差別是實現了一個跨平臺的使用者態緩衝的解決方案。緩衝區可以減少系統呼叫的次數,提高執行效率。C標準庫是系統呼叫的封裝,在內部區分了作業系統,可實現跨平臺使用。


1、開啟和關閉檔案:

系統呼叫函式:

函式原型:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int close(int fd);

程式碼示例:

int fd;
if (fd = open("test.txt",O_RDONLY | O_CREAT,O_IWOTH) == -1)
{
	printf ("檔案開啟失敗\n");
	perror ("open");
}
close(fd);

標準I/O函式:

函式原型:

FILE *fopen(const char *path, const char *mode);
FILE *fdopen(int fildes, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *stream);
int fclose(FILE *fp);

程式碼示例:

FILE *fp = fopen("abc","a");
if(fp == NULL)
{
	perror("fopen");
	return -1;
}
printf ("檔案開啟成功\n");
	
fclose (fp);

2、讀檔案和寫檔案:

系統呼叫函式:

函式原型:

ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);

程式碼示例(複製檔案):

int fd1 = open("1.ppt",O_RDONLY);
if (fd1 == -1)
{
	perror("open");
}
int fd2 = open("2.ppt",O_WRONLY | O_CREAT);
if (fd2 == -1)
{
	perror("open");
}
int ret = 0;
char buf[SIZE] = {0};
while (ret = read(fd1,buf,SIZE))
{
	if (ret == -1)
	{
		perror ("raed");
		break;
	}
	write (fd2,buf,ret);
}
printf ("檔案複製成功\n");
close (fd1);
close (fd2);

標準I/O函式:

函式原型:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

程式碼示例:

FILE *fp1 = fopen("1.ppt","a");
if(fp1 == NULL)
{
	perror("fopen");
	return -1;
}
FILE *fp2 = fopen("1.ppt","a");
if(fp2 == NULL)
{
	perror("fopen");
	return -1;
}
printf ("檔案開啟成功\n");
int ret = 0;
char buf[SIZE] = {0};
while (ret = fread(buf,sizeof(char),SIZE,fp1))
{
	fwrite(buf,sizeof(char),ret,fp2);
}
if (ret == 0 && !feof(fp1))
{
	perror ("fraed");
	return -1;
}
printf ("檔案複製成功\n");

3、移動檔案偏移指標:

系統呼叫函式:

函式原型:

off_t lseek(int fildes, off_t offset, int whence);

程式碼示例1:

int fd;
if ((fd = open("test",O_RDWR | O_CREAT,0777)) == -1)
{
	printf ("檔案開啟失敗\n");
	perror ("open");
}

lseek (fd,15,SEEK_SET);
write(fd,"abc",4);
close(fd);

程式碼例項2:(建一個1G的大檔案)

int fd;
if ((fd = open("big",O_RDWR | O_CREAT,0777)) == -1)
{
	printf ("檔案開啟失敗\n");
	perror ("open");
}
	
lseek (fd,1024*1024*1024,SEEK_SET);
write(fd,"\0",1);
close(fd);

關於檔案程式設計的更多函式及其使用,歡迎大家一起交流。