file *fopen(const char *filename, const char *mode)
filename 開啟的檔案名稱 mode 開啟模式
返迴文件指標
size_t fread(void *ptr, size_t size, size_t, file *stream)
從stream指向的檔案中讀取n個欄位,每個欄位為size位元組,並將讀取的資料放在ptr所指的字元數組中,返回實際讀取位元組數
size_t fwrite(const void *ptr, size_t size, size_t n, file *stream)
從緩衝區ptr所指的數組中把n個欄位寫到stream指向的檔案中,每個欄位長為size個位元組,返回實際寫入的欄位數。
從指定檔案中讀取一個字元
例子 1:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
file *fp;
char ch;
if((fp = fopen("test.txt","rt")) == null)
{
printf("file open error!");
exit(1);
}
ch = fgetc(fp);
while(ch != eof)
{
putchar(ch);
ch = fgetc(fp);
}
fclose(fp);
}
int fputc(int c, file *stream)
向指定的檔案中寫入一個字元
例子 2:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
file *fp;
char ch;
if((fp = fopen("test.txt","wt+")) == null)
{
printf("file open error!");
exit(1);
}
printf("please enter a stringn");
ch = getchar();
while(ch != 'n')
{
fputc(ch, fp);
ch = getchar();
}
fclose(fp);
}
fscanf(file *stream, char *format [,argument...])
從一個流中進行格式化輸入
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
printf("please enter an interger:");
if(fscanf(stdin, "%d",&i)) //從標準輸入資料流讀取
printf("the interger is :%dn",i);
return 0;
}
int fprintf(file *stream, char *format[,argument...])
格式化輸出到一個流中
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
file *stream;
int i = 10;
double fp = 1.5;
char s[] = "hello world";
char c = 'n';
stream = fopen("fprint.out", "w");
fprintf(stream, "%s%c", s, c);
fprintf(stream, "%dn", i);
fprintf(stream, "%fn", fp);
fclose(stream);
return 0;
}
int fseek(file *stream, long offset, int whence)
設定檔案指標whence :
seek_set:從檔案的開始處開始搜尋
seek_cur:從當前位置開始搜尋
seek_end:從檔案結尾處開始搜尋