1格式化打开
#include<stdio.h>
FILE *fopen(const char * restrict pathname,const char *restrict type)
功能:打开一个指定文件
参数:typer 读
w写
a 追加
r+ 读写
返回值:成功,文件指针;失败,NULL
2格式化关闭
#include<stdio.h>
int fclose(FILE *fp)
功能:关闭一个文件
参数:
返回值:成功,0;失败,EOF
3格式化输出
#include<stdio.h>
int fprintf(FILE *restrict fp,const char *restrict format,……)
功能:将指定格式数据输入到文件(流)
参数:format为格式字符串
返回值:成功,字符数;失败,负值
4 格式化输入
#include<stdio.h>
int fscanf(FILE *restrict fp,const char *restrict format,……)
功能:从文件(流)中输入格式化数据
参数:format为格式字符串
返回值:成功,指定的输入项数;格式匹配失败失败或者到达文件尾部,EOF
实例:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#define FILENAME "test.txt"
#define NSERVER 10
#define IPLEN 16
void main(){
char buf[NSERVER][IPLEN];
FILE* ffd;
int nbytes;
int servernum = 0;
if(NULL == (ffd = fopen(FILENAME,"r"))){
perror("fopen error");
exit(1);
}
int i;
for(i=0;i<NSERVER;i++){
if(EOF == (nbytes = fscanf(ffd,"%s",buf[i]))){
perror("Fscanf error");
exit(1);
}
printf("%s:%d:%d\n",buf[i],strlen(buf[i]),nbytes);
servernum++ ;
}
if(-1 == close(ffd)){
perror("Close error");
exit(1);
}
}