C語言學習筆記-文件讀寫函數彙總

一、打開文件

FILE *fopen( const char * filename, const char * mode );

FILE指的是C語言的文件類型,其在stdio.h中有定義;
filename指的是文件路徑與文件名,格式爲"磁盤:/文件夾/文件名.文件類型",例如:“C:/qaq/test.txt”(特別注意是左斜槓,不是右斜槓);
mode指的是文件打開的模式。

模式全覽

二、關閉文件

int fclose( FILE *fp );

該函數是有int類型返回值的,當文件被成功關閉時,函數返回值爲,關閉文件失敗時將返回EOF

三、寫入文件

1、fputc函數

int fputc( int c, FILE *fp );

作用:向文件中輸入一個字符,若成功輸入則返回輸入的值,若失敗則返回EOF。在C語言中,#define EOF (-1) 。
特別注意:程序中所寫的int類型在寫入文本文件時會按照ASCII碼被自動轉化爲char類型。如:fputc( 65, fp ); 在文檔中爲:A

2、fputs函數與fprintf函數

int fputc( int c, FILE *fp );
int fputs( const char *s, FILE *fp );

作用:向文件中輸入一個字符串,若成功輸入則返回一個非負值,若失敗則返回EOF

四、讀取文件

1、fgetc函數

int fgetc( FILE * fp );

作用:讀取文件中的一個字符,若成功則返回讀取的字符,若失敗則返回EOF

2、fgets函數

char *fgets( char *buf, int n, FILE *fp );

buf指的是存放讀取字符的數組;
n指的是讀取字符的長度,當讀到第n-1個字符時,會在之後加一個NULL表示終止字符串;
作用:讀取文件中的n個字符,若成功則返回讀取的字符,若文檔提前結束(也即遇到EOF)或遇到換行符\n,則自動加入終止符NULL

3、fscanf函數

int fscanf( FILE *fp, const char *format, ... );

作用:讀取文件中的字符,若遇到空格則會自動加入終止符NULL

4、fseek函數

int fseek ( FILE *fp, long int offset, int whence );

offset指的是偏移量;
whence指的是參考點,包括: SEEK_SET(文件頭)SEEK_CUR(文件中的標記點)SEEK_END(文件尾)
作用:在指定位置對文件進行輸入,且只改變輸入量的部分,而不影響文檔其他部分

實例:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp=NULL;  
    int a,ch;
    
    if((fp=fopen("C:/qaq/test.txt","w"))==NULL)
    {
        printf("file cannot open \n");
        exit(0);  
        //exit結束程序,一般0爲正常推出,其它數字爲異常,其對應的錯誤可以自己指定。
    }
    else
    {
		printf("file opened for writing \n");
		fprintf(fp, "I like to study C.\n");	//fprinf
		a=fputc( 65, fp );	//fputc
   		printf("%c \n",a);
   		fputs("\nI qpink it's interesting. \n", fp);	//fputs
   		fseek ( fp , 24 , SEEK_SET );	//fseek
		fputs ( " th" , fp );
	}
	
    if(fclose(fp)!=0)
        printf("file cannot be closed \n");
    else
        printf("file is now closed \n");
    
    if((fp=fopen("C:/qaq/test.txt","r"))==NULL)
    {
        printf("file cannot open \n");
        exit(0);  
    }
    else
    {
		printf("file opened for reading \n");
		while((ch=fgetc(fp))!=EOF)
			putchar(ch);
			printf("\n");
	}
    if(fclose(fp)!=0)
        printf("file cannot be closed \n");
    else
        printf("file is now closed \n");
    return 0;
}

運行結果如下:
運行結果

發佈了12 篇原創文章 · 獲贊 22 · 訪問量 3448
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章