1. 读写字符函数fgetc(),fputc()
int fgetc(FILE *stream);
将流指针指向的文件中的一个字符输出。若文件指针指到文件尾,会遇到文件结束标志EOF(-1),我们可以通过检查该函数的返回值是否是-1来判断是否已读到文件尾。
int fputc(int ch,FILE *stream);
将字符变量ch的值写到流指针指定的文件中去,若是stdout是标准输出(显示器),将会在显示器上打印出来。
举例1:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
FILE *fp=NULL;
char ch;
if((fp=fopen("D:\\my.txt","r"))==NULL)
{
printf("can not open the file.\n");
exit(0);
}
while((ch=fgetc(fp))!=EOF)
fputc(ch,stdout);
printf("\n");
fclose(fp);
system("pause");
return 0;
}
用只读方式打开一个文本文件,并逐字符读取和输出。
输出结果:
2. 读写字符串函数fgets(),fputs(),检测文件结束符函数feof()
char *fgets(char *buf, int bufsize, FILE *stream);
从文件结构体指针stream中读取数据,每次读取一行。读取的数据保存在buf指向的字符数组中,每次最多读取bufsize-1个字符(第bufsize个字符赋'\0').如果文件中的该行,不足bufsize个字符,则读完该行就结束。如若该行(包括最后一个换行符)的字符数超过bufsize-1,则fgets只返回一个不完整的行.但是,缓冲区总是以NULL('\0')字符结尾,对fgets的下一次调用会继续读该行。函数成功将返回buf,失败或读到文件结尾返回NULL。因此我们不能直接通过fgets的返回值来判断函数是否是出错而终止的,应该借助feof函数或者ferror函数来判断。
int fputs(char *str,FILE *stream);
向指定的文件写入一个字符串(不自动写入字符串结束标记符‘\0’)。成功写入一个字符串后,文件的位置指针会自动后移,返回值为非负整数;否则返回EOF(符号常量,其值为-1)。
int feof(FILE *stream);
检测流上的文件结束符,如果文件结束,则返回非0值,否则返回0.
EOF是文本文件结束的标志。在文本文件中,数据是以字符的ASCⅡ代码值的形式存放,普通字符的ASCⅡ代码的范围是32到127(十进制),EOF的16进制代码为0xFF(十进制为-1),因此可以用EOF作为文件结束标志。
举例2:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
FILE *fp=NULL;
char ch[30];
if((fp=fopen("D:\\my.txt","r"))==NULL)
{
printf("can not open the file.\n");
exit(0);
}
while(!feof(fp))
{
if(fgets(ch,30,fp)!=NULL)
printf("%s\n",ch);
}
fclose(fp);
system("pause");
return 0;
}
输出结果:
可以看出文本文档中有两行,中间有一个换行符。
3. 读写流文件流函数fread(),fwrite()
fread函数原型:
size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;
参数:
buffer:用于接收数据的内存地址。
size:要读的每个数据项的字节数,单位是字节,一般是1.
count:要读的数据项的个数
stream:文件输入流
返回值:实际读取的元素个数。
fwrite函数原型:
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
参数:
buffer:要写入的数据的内存地址。
size:要写的每个数据项的字节数。
count:要写的数据项的个数。
stream:文件指针
返回值:实际写入的数据块数目。
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
/*#ifdef __cplusplus
cout<<"c++"<<endl;
#else
cout<<"c";
#endif
cout<<__FILE__<<endl;
cout<<__LINE__<<endl;
*/
char c;
char *str = "You are a good boy.";
char gets_buffer[100];
char read_buffer[100];
FILE *fp = fopen("file.txt","w");
fputc('c',fp);
fputs(str,fp);
fwrite("This is a book",1,15,fp);
fclose(fp);
FILE *f = fopen("file.txt","r");
c = fgetc(f);
printf("fgetc is %c\n",c);
fgets(gets_buffer,20,f);
printf("fgets is %s\n",gets_buffer);
fread(read_buffer,1,15,f);
printf("fread is %s\n",read_buffer);
system("pause");
return 0;
}
输出结果: