http://blog.csdn.net/ding285119896/article/details/13161947
C语言标准路为我们提供了文件操作函数:
包含:fopen()/fclose() //文件打开与关闭函数;(参数与返回类型省略)
fgetc()/fputc() //从流中获取字符,向文件流中写入字符;
getc()/putc() //与fgetc()/fputc()等价,不同的是,当getc()/putc()定义为宏时,可能多次计算stream的值;
getchar()/putchar() //与上述两种类似;
ungetc() //将字符转化为unsigned char 类型写回到流中;
fscanf()/fprintf() //用于文件的格式化输入输出;
fread()/fwrite() //从流中读/写特定数目的特定单位大小的对象;
fgets()/fputs() //从文件流中获取字符串,或将字符串写入流中;
其中char* fgets(char*s,int size,FILE*fp)最多将size-1个字符读入s中,s的第size个存储空间保留‘\0’,因而s中保留的为字符串,对于文件,如遇到换行符,读取结束。即:当size大于文件一行的字符数时,fgets()运行一次读取文件中的一行,否则,一次读取特定数目的字符。(在实际中,当s由动态分配获得时,读取失败 ,只能采取静态分配这是为什么,求解?)。
文件定位函数:
int fseek(FILE*stream,long offset,int orign)
对于二进制流,被设置为origin开始的第offset个字符处,origin:SEEK_SET,SEEK_CUR,SEEK_END;
对于文本流,offset必须设置为0,获是ftell()的返回值(此时origin必须设置为SEEK_SET;
int ftell(FILE*stream) //返回stream流的当前文件位置;
void rewind() //即:fseek(fp,0L,SEEK_SET);clearerr(fp);
int fgetpos(FILE*stream,fpos_t *ptr) //获取流的当前位置,记录在*ptr中
int fsetpos(FILE*stream,const fpos_t *ptr) //将流的当前位置设置为*ptr中的位置
int feof(fp) 文件是否到文件结束符,若是,则返回非0值,否则返回0。
例子:从文件name1中查找字符串,并替换为另一个字符串,结果保存在name2文件中
1、替换字符串中的特定字符串
1、替换字符串中的特定字符串
[cpp] view plain copy
voidSubstitute(char*pInput,char*pOutput,char*pSrc,char*pDst)
{
char*pi, *po, *p;
intnSrcLen, nDstLen, nLen;
// 指向输入字符串的游动指针.
pi = pInput;
// 指向输出字符串的游动指针.
po = pOutput;
// 计算被替换串和替换串的长度.
nSrcLen = strlen(pSrc);
nDstLen = strlen(pDst);
// 查找pi指向字符串中第一次出现替换串的位置,并返回指针(找不到则返回null).
p = strstr(pi, pSrc);
if(p)
{
// 找到.
while(p)
{
//计算被替换串前边字符串的长度.
nLen = (int)(p - pi);
// 复制到输出字符串.
memcpy(po, pi, nLen);
memcpy(po + nLen, pDst, nDstLen);
// 跳过被替换串.
pi = p + nSrcLen;
// 调整指向输出串的指针位置.
po = po + nLen + nDstLen;
// 继续查找.
p = strstr(pi, pSrc);
}
// 复制剩余字符串.
strcpy(po, pi);
}
else
{
// 没有找到则原样复制.
strcpy(po, pi);
}
} 测试程序:
[cpp] view plain copy
intmain()
{
FILE*fpSrc,*fpDes;
charfilename1[20]="ding1.txt";
charfilename2[20]="ding2.txt";
//要求查找的字符串,替换的字符串;
charps[]="computer";
charpd[]="basketballs";
//求取所查找和替换的字符串的长度;
intlen_src=strlen(ps);
intlen_des=strlen(pd);
//定义存储字符串缓冲区;很奇怪的一点是,fgets函数不能将字符串写入动态分配的内存中
charSrc_buf[MAXSIZES];
charCpy_buf[MAXSIZES];
charDes_buf[MAXSIZES];
//打开文件
if((fpSrc=fopen(filename1,"r+"))==NULL)
{
printf("fail to open the file1 !\n");
exit(1);
}
if((fpDes=fopen(filename2,"a+"))==NULL)
{
printf("fail to open the file2 !\n");
exit(1);
}
//进行循环读取
while(!feof(fpSrc))//判断文件是否已结束;!feof(fpSrc)
{
fgets(Src_buf,MAXSIZES,fpSrc);
Substitute(Src_buf,Des_buf,ps,pd);
fputs(Des_buf,fpDes);
printf("%s",Des_buf);
}
fclose(fpSrc);
fclose(fpDes);
system("pause");
return0;
}