fopen
原型:FILE * fopen(const char * path, const char * mode)
打開文件
#include <stdio.h>
int main(){
FILE *fp = fopen("hello.c", "r");
if(fp){
printf("success\n");
}else{
printf("error\n");
}
return 0;
}
fclose
原型:int fclose(FILE *stream)
關閉文件
FILE *fp = fopen("hello.c", "r");
// ...
fclose(fp)
getc
原型: int getc(FILE *stream)
一次讀一個字符
#include <stdio.h>
int main(){
FILE *fp = fopen("hello.c", "r");
if(fp){
while(1){
char c = getc(fp);
if(c == EOF){
break;
}
printf("%c", c);
}
fclose(fp);
}
return 0;
}
putc
原型:int fputc(int ch,FILE*fp)
一次寫一個字符
#include <stdio.h>
int main(){
FILE *fp = fopen("a.txt", "w");
if(fp){
putc('a', fp);
fclose(fp);
}
return 0;
}
fgets和fputs
詳見C語言字符串相關函數
fscanf
原型:int fscanf(FILE*stream,constchar*format,[argument...])
從一個流中執行格式化輸入,fscanf遇到空格和換行時結束。這與fgets有區別,fgets遇到空格不結束。
fprintf
原型:int fprintf (FILE* stream, const char*format, [argument])
fprintf( )會根據參數format 字符串來轉換并格式化數據, 然后將結果輸出到參數stream 指定的文件中, 直到出現字符串結束('\0')為止
stat
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(){
struct stat st = {0};
stat("a.txt", &st);
int size = st.st_size; // 文件大小
// ...
}
fwrite
原型:size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream)
這個函數是指,從buffer地址開始獲取數據,往stream文件中寫入count個size字節的內容
#include <stdio.h>
int main(){
FILE *fp = fopen("test.txt", "w");
int a = 100;
fwrite(&a, sizeof(int), 1, fp);
fclose(fp);
return 0;
}
fread
原型:size_t fread (void *buffer, size_t size, size_t count, FILE *stream)
fread返回讀到的size的個數。
#include <stdio.h>
int main(){
FILE *fp = fopen("test.txt", "r");
int a = 0;
fread(&a, sizeof(int), 1, fp);
fclose(fp);
return 0;
}
fseek
原型:int fseek(FILE *stream, long offset, int fromwhere)
設置文件指針stream的位置。stream將指向以fromwhere為基準,偏移offset(指針偏移量)個字節的位置。
ftell
原型:long ftell(FILE *stream)
使用fseek函數后再調用函數ftell()就能非常容易地確定文件的當前位置。
fflush
原型:int fflush(FILE *stream)
fflush()會強迫將緩沖區內的數據寫回參數stream 指定的文件中. 如果參數stream 為NULL,fflush()會將所有打開的文件數據更新。
remove
原型:int remove(const char *filename)
刪除文件。
rename
原型:int rename(char *oldname, char *newname)
文件重命名。