#include<stdio.h>
#include<conio.h>
main(){
FILE *fp;
char c;
if((fp=fopen("d:\\a.txt","rt"))==NULL){
printf("\n cannot open file and exit!");
_getch();
exit(1);
}
c = fgetc(fp);
while(c!=EOF){
putchar(c);
c=fgetc(fp);
}
fclose(fp);
_getch();
}
上边是读取一个文件的内容。
首先定义文件指针fp 然后让fp指向对应文件 如果fopen打开文件出错,则exit, “rt”表示只读
如果成功继续,读取第一个字符,循环判断是否到达末尾(EOF),循环读取。最后别忘了关闭。 注意fgetc函数。
#include<stdio.h>
#include<conio.h>
main(){
FILE *fp;
char c;
if((fp=fopen("d:\\append.txt","wt+"))==NULL){
printf("\n cannot open file and exit!");
_getch();
exit(1);
}
scanf("input a string : \n");
c = getchar();
while(c!='\n'){
fputc(c,fp);
c = getchar();
}
fclose(fp);
_getch();
}
前边一样,获取输入的第一个字符,循环判断,知道判断出最后一个字符(回车键), 每次循环把这个char put到对应的文件指针,即写入。注意fputc函数。
#include<stdio.h>
#include<conio.h>
main(){
FILE *fp;
char str[11];
if((fp=fopen("d:\\a.txt","rt"))==NULL){
printf("\n cannot open file and exit!");
_getch();
exit(1);
}
fgets(str,11,fp);
printf("\n%s\n",str);
fclose(fp);
_getch();
}
还要注意一个函数 fgets, 比如上边的fgets(str,11,fp)表示从文件指针中获取11个字符的长度,并把获取的值赋值给str。
#include<stdio.h>
#include<conio.h>
main(){
FILE *fp;
char ch, str[100];
if((fp=fopen("d:\\a.txt","at+"))==NULL){
printf("\n cannot open file and exit!");
_getch();
exit(1);
}
printf("input a string: \n");
scanf("%s",str);
fputs(str,fp);
fclose(fp);
_getch();
}
fputs就不解释了,很明了。
#include<stdio.h>
#include<conio.h>
main(){
FILE *fp;
char ch, str[100];
if((fp=fopen("d:\\a.txt","wb+"))==NULL){
printf("\n cannot open file and exit!");
_getch();
exit(1);
}
char write[26] = "abcdefghijklmnopqrstuvwxyz";
fwrite(write,4,4,fp);
rewind(fp);
fread(str, 4, 4, fp); // 在这之前需要rewind到开始
printf("%s \n",str);
printf("operate is over \n");
fclose(fp);
_getch();
}
fread函数和fwrite函数。
fwrite代表把write的值每次4字节,连续写4次,写入到fp文件指针。
同理fread。
需要说明的是示例中的rewind函数,fwrite操作后,操作指向了文件末尾,这时候需要重新指向文件开始。否则直接读出来会是空。
最后介绍介个函数,做判断用。
1. feop(文件指针) 判断文件是否处于结束位置
2. feeror(文件指针) 检查文件读写是否出错,返回为0 表示正确
3. cleanerr(文件指针) 清楚出错标志和文件结束标志
最后,给出文件方式缩写表: