字符读取函数 fgetc
#include<stdio.h>
int main(){
FILE *fp;
char ch;
//如果文件不存在,给出提示并退出
if( (fp=fopen("D:\\demo.txt","rt")) == NULL ){
printf("Cannot open file, press any key to exit!");
getch();
exit(1);
}
//每次读取一个字节,直到读取完毕
while( (ch=fgetc(fp)) != EOF ){//end of file
putchar(ch);
}
putchar('\n'); //输出换行符
fclose(fp);
return 0;
}
feof() 函数用来判断文件内部指针是否指向了文件末尾,它的原型是:
int feof ( FILE * fp );
当指向文件末尾时返回非零值,否则返回零值。
ferror() 函数用来判断文件操作是否出错,它的原型是:
int ferror ( FILE *fp );
出错时返回非零值,否则返回零值。
if(ferror(fp)){
puts("读取出错");
}else{
puts("读取成功");
}
字符写入函数fputc
#include<stdio.h>
int main(){
FILE *fp;
char ch;
//判断文件是否成功打开
if( (fp=fopen("D:\\demo.txt","wt+")) == NULL ){
printf("Cannot open file, press any key to exit!\n");
getch();
exit(1);
}
printf("Input a string:\n");
//每次从键盘读取一个字符并写入文件
while ( (ch=getchar()) != '\n' ){//每次取出一个字符
fputc(ch,fp);//进行字符写入
}
fclose(fp);
return 0;
}
读字符串函数fgets
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main(){
FILE *fp;
char str[N+1];
if( (fp=fopen("d:\\demo.txt","rt")) == NULL ){
printf("Cannot open file, press any key to exit!\n");
getch();
exit(1);
}
while(fgets(str, N, fp) != NULL){
printf("%s", str);
}
fclose(fp);
system("pause");
return 0;
}
fgets() 遇到换行时,会将换行符一并读取到当前字符串。该示例的输出结果之所以和 demo.txt 保持一致,该换行的地方换行,就是因为
fgets() 能够读取到换行符。而 gets() 不一样,它会忽略换行符。
写字符串函数fputs
#include<stdio.h>
int main(){
FILE *fp;
char str[102] = {0}, strTemp[100];
if( (fp=fopen("D:\\demo.txt", "at+")) == NULL ){
printf("Cannot open file, press any key to exit!\n");
getch();
exit(1);
}
printf("Input a string:");
gets(strTemp);
strcat(str, "\n");
strcat(str, strTemp);
fputs(str, fp);
fclose(fp);
return 0;
}