Linux輸入輸出與檔案,Linux輸入輸出檔案
1. 基於檔案指標的檔案操作(緩衝)
linux中對目錄和裝置的操作都是檔案操作,檔案分為普通檔案,目錄檔案,連結檔案和裝置檔案。
1.1. 檔案的建立,開啟與關閉
原型為:
#include <stdio.h> //標頭檔包含
FILE *fopen(const char *pach,const char *mode); //檔案名稱 模式
int fclose(FILE *stream);
fopen以mode的方式開啟或建立檔案,如果成功,將返回一個檔案指標,失敗則返回NULL.
fopen建立的檔案的存取權限將以0666與當前的umask結合來確定。
1.2. 讀寫檔案
基於檔案指標的資料讀寫函數較多,可分為如下幾組:
資料區塊讀寫:
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream);
fread從檔案流stream 中讀取nmemb個元素,寫到ptr指向的記憶體中,每個元素的大小為size個位元組。
fwrite從ptr指向的記憶體中讀取nmemb個元素,寫到檔案流stream中,每個元素size個位元組。
所有的檔案讀寫函數都從檔案的當前讀寫點開始讀寫,讀寫完以後,當前讀寫點自動往後移動size*nmemb個位元組。
1.3.檔案定位:
檔案定位指讀取或設定檔案當前讀寫點,所有的通過檔案指標讀寫資料的函數,都是從檔案的當前讀寫點讀寫資料的。
常用的函數有:
#include <stdio.h>
int feof(FILE * stream); //通常的用法為while(!feof(fp))
int fseek(FILE *stream, long offset, int whence);//設定當前讀寫點到位移whence 長度為offset處
long ftell(FILE *stream); //用來獲得檔案流當前的讀寫位置
void rewind(FILE *stream); //把檔案流的讀寫位置移至檔案開頭 èfseek(fp, 0, SEEK_SET);
feof判斷是否到達檔案末尾的下一個(注意到達檔案末尾之後還會做一次)
fseek設定當前讀寫點到位移whence 長度為offset處,whence可以是:
SEEK_SET (檔案開頭 –>0)
SEEK_CUR (檔案當前位置 –>1)
SEEK_END (檔案末尾 –>2)
ftell擷取當前的讀寫點
rewind將檔案當前讀寫點移動到檔案頭
1.4.格式化讀寫:
#include <stdio.h>
int printf(const char *format, ...); //相當於fprintf(stdout,format,…);
int scanf(const char *format, …);
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, …);
int sprintf(char *str, const char *format, ...); // eg: sprintf(buf,”the string is;%s”,str);
int sscanf(char *str, const char *format, …);
以f開頭的將格式化後的字串寫入到檔案流stream中
以s開頭的將格式化後的字串寫入到字串str中
1.5.單個字元讀寫:
使用下列函數可以一次讀寫一個字元
#include <stdio.h>
int fgetc(FILE *stream);
int fputc(int c, FILE *stream);
int getc(FILE *stream); è 等同於 fgetc(FILE* stream)
int putc(int c, FILE *stream); è 等同於 fputc(int c, FILE* stream)
int getchar(void); è 等同於 fgetc(stdin);
int putchar(int c); è 等同於 fputc(int c, stdout);
getchar和putchar從標準輸入輸出資料流中讀寫資料,其他函數從檔案流stream中讀寫資料。
1.6.字串讀寫:
char *fgets(char *s, int size, FILE *stream);
int fputs(const char *s, FILE *stream);
int puts(const char *s); è 等同於 fputs(const char *s, int size, stdout);
char *gets(char *s); è 等同於 fgets(const char *s, int size, stdin);
fgets和fputs從檔案流stream中讀寫一行資料;
puts和gets從標準輸入輸出資料流中讀寫一行資料。
fgets可以指定目標緩衝區的大小,所以相對於gets安全,但是fgets調用時,如果檔案中當前行的字元個數大於size,則下一次fgets調用時,將繼續讀取該行剩下的字元,fgets讀取一行字元時,保留行尾的分行符號。
fputs不會在行尾自動添加分行符號,但是puts會在標準輸出資料流中自動添加一分行符號。