Linux系統編程5標準IO - cfgets和fputs

實驗1:fgets 正常結束情況說明
實驗2:以字符串拷貝的方式實現cp, fgets(),fputs()


1 fgets說明

/*
讀取文件後的存儲地址
讀取大小
源文件
*/
char *fgets(char *s, int size, FILE *stream);

返回值:
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.
成功返回s地址,失敗或者讀完 返回空指針。

兩種可能造成該函數的正常結束

情況1,讀到了 size-1 個有效字節,爲什麼只讀取SIZE-1個字節,因爲讀取的是一個字符串。所以最後剩下一個字節位是要存 ‘\0’ 的。

情況2,遇到 ‘\n’換行符, '\n’表示當前字符串的結束

實驗1:fgets 正常結束情況說明

#define SIZE 5
char buf[SIZE];
char *fgets(buf, SIZE, stream);

情況1,如果文件中的內容是 abcdef,那麼第一次讀取的時候,那5個字節的空間中存儲的分別是 a b c d \0,讀完後當前文件的當前位置指針是在e這個位置處。

情況2,如果文件中的內容是 ab, 對該文件進行讀取的話,讀完ab 之後, 其實後面還有一個字符‘\n’,也會被讀取。 所以對該文件讀取之後,buf 中存儲的內容就是 a b \n \0,其中\0是自動補的。

注意:當我們vim 打開一個空文檔時候,只要進入編輯模式,即使沒有輸入,但是其實該空文檔也是有一個字符的,該字符就是第一行默認的‘\n’換行符。即使是文件最後一行的內容,結尾也有 ‘\n’換行符。

情況3:擦邊球情況
如果文件中的內容是 abcd,如果用上面fgets()讀取,需要讀幾次才能讀取完該文件 ,需要讀兩次。
第一次 -> a b c d ‘\0’,讀到了 SIZE-1個字符
第二次 -> ‘\n’ ‘\0’


2 fputs說明

int fputs(const char *s, FILE *stream);

DESCRIPTION
fputs() writes the string s to stream, without its terminating null byte (’\0’).

實驗2 以字符串拷貝的方式實現cp, fgets(),fputs()

#include<stdio.h>
#include<stdlib.h>

#define BUFSIZE 1024

int main(int argc,char *argv[])
//int main(int argc,char **argv)
{
	FILE *fps,*fpd;
	char buf[BUFSIZE];

	if(argc < 3)
	{
	fprintf(stderr,"Usage:%s <src_file> <dest_file>\n",argv[0]);
	exit(1);
	}

	fps = fopen(argv[1],"r");
	if(fps == NULL)
	{
		perror("fopen()");
		exit(1);
	}

	fpd = fopen(argv[2],"w");
	if(fpd == NULL)
	{
		fclose(fps);
		perror("fopen()");
		exit(1);
	}

	while(fgets(buf,BUFSIZE,fps) != NULL)
	{
		fputs(buf,fpd);
	}
	
	fclose(fpd);
	fclose(fps);
}


mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ 
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ 
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ gcc mycpy_fgets.c 
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ ll
total 28
drwxrwxr-x 2 mhr mhr 4096 Apr 19 06:55 ./
drwxrwxr-x 4 mhr mhr 4096 Apr 19 06:45 ../
-rwxrwxr-x 1 mhr mhr 9024 Apr 19 06:55 a.out*
-rw-rw-r-- 1 mhr mhr  531 Apr 19 06:55 mycpy_fgets.c
-rw-rw-r-- 1 mhr mhr   11 Apr 19 03:36 test1
-rw-rw-r-- 1 mhr mhr    0 Apr 19 06:45 test2
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ ./a.out test1 test2
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ ll
total 32
drwxrwxr-x 2 mhr mhr 4096 Apr 19 06:55 ./
drwxrwxr-x 4 mhr mhr 4096 Apr 19 06:45 ../
-rwxrwxr-x 1 mhr mhr 9024 Apr 19 06:55 a.out*
-rw-rw-r-- 1 mhr mhr  531 Apr 19 06:55 mycpy_fgets.c
-rw-rw-r-- 1 mhr mhr   11 Apr 19 03:36 test1
-rw-rw-r-- 1 mhr mhr   11 Apr 19 06:55 test2
mhr@ubuntu:~/work/linux/stdio/mycpy_fgets$ 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章