C语言文件操作(一)
来源:百度文库 编辑:神马文学网 时间:2024/10/02 21:25:44
C语言提供了4种标准读写文件的方法,相应的也有4种函数:1.fgetc 和 fputc 读写一个字符2.fgets 和 fputs 读写一个字符串3.fscanf 和 fprintf 格式化读写4.fread 和 fwrite 读写数据块,二进制数据读写 读取文本文件的程序示例://读取文本文件的内容 #include "stdafx.h" int main(int argc, char* argv[])
{
//文件结构指针
FILE *fp;
//只读的方式打开文件
fp=fopen("E:/test.txt","r");
//容错处理
if(fp==NULL)
{
printf("文件不存在!");
return 0;
}
char str[100];
char *tempStr;
do
{
tempStr=fgets(str,100,fp);
if(tempStr!=NULL)
printf("%s\n",str);
}while(!feof(fp));//判断是否文件结尾 //关闭文件指针
fclose(fp); return 0;
}
文件的复制,同时适用于二进制文件和文本文件// FileTest.cpp : Defines the entry point for the console application.
//文件的复制 #include "stdafx.h" int main(int argc, char* argv[])
{
//文件结构指针
FILE *fp;
FILE *cp;
//只读的方式打开文件
fp=fopen("E:/test.txt","r");
cp=fopen("E:/copyTest.txt","w");
//容错处理
if(fp==NULL)
{
printf("文件不存在!");
return 0;
}
char str[100];
//返回的已经读取的文件指针位置
unsigned int temp;
do
{
temp=fread(str,sizeof(char),100,fp);
fwrite(str,sizeof(char),temp,cp);
}while(temp==100);//判断是否文件结尾 //关闭文件指针
fclose(fp);
fclose(cp);
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liyebing/archive/2008/11/30/3410716.aspx
{
//文件结构指针
FILE *fp;
//只读的方式打开文件
fp=fopen("E:/test.txt","r");
//容错处理
if(fp==NULL)
{
printf("文件不存在!");
return 0;
}
char str[100];
char *tempStr;
do
{
tempStr=fgets(str,100,fp);
if(tempStr!=NULL)
printf("%s\n",str);
}while(!feof(fp));//判断是否文件结尾 //关闭文件指针
fclose(fp); return 0;
}
文件的复制,同时适用于二进制文件和文本文件// FileTest.cpp : Defines the entry point for the console application.
//文件的复制 #include "stdafx.h" int main(int argc, char* argv[])
{
//文件结构指针
FILE *fp;
FILE *cp;
//只读的方式打开文件
fp=fopen("E:/test.txt","r");
cp=fopen("E:/copyTest.txt","w");
//容错处理
if(fp==NULL)
{
printf("文件不存在!");
return 0;
}
char str[100];
//返回的已经读取的文件指针位置
unsigned int temp;
do
{
temp=fread(str,sizeof(char),100,fp);
fwrite(str,sizeof(char),temp,cp);
}while(temp==100);//判断是否文件结尾 //关闭文件指针
fclose(fp);
fclose(cp);
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liyebing/archive/2008/11/30/3410716.aspx