读写文件
文件操作中,最频繁的就是文件的读写操作了。在C语言里,可以使用fread/fwrite,fscanf/fprintf,fgets/fputs,fgetc/fputc等函数来进行文件的读写。总的来说,C语言中文件的读写分为如下几种形式:
11.5.1 二进制文件读写
int binary_io()
{
//打开或者创建文件
char *path = "h:\\doc\\new.txt";
FILE *fp1 = NULL;
errno_t err;
err = fopen_s(&fp1,path,"w");
if(fp1==NULL || err != 0)
{
printf("Open file failed\n");
return -1;
}
//基于fp1这个指针,对文件进行读写等操作
char buff[]="hello world";
fwrite(buff,sizeof(buff),1,fp1);
int data = 0x10;
fwrite(&data,sizeof(data),1,fp1);
fclose(fp1);
//读数据
err = fopen_s(&fp1,path,"r");
if(err!=0)
{
return -1;
}
data = 0;
memset(buff,0,sizeof(buff));
fread(buff,sizeof(buff),1,fp1);
printf("buff:%s\n", buff);
fread(&data,sizeof(data),1,fp1);
printf("data:0x%x\n",
data);
fclose(fp1);
return 0;
}
11.5.2 格式化输入输出到文本文件。
将除了ascci之外的数据以文本的方式写入文件
int format_io()
{
char *file="h:\\doc\\1.txt";
FILE *pfile=NULL;
errno_t err = fopen_s(&pfile,file,"w");
if(err!=0 || pfile==NULL)
{
printf("Open file failed\n");
return -1;
}
fprintf(pfile,"%s %x %lf","hello-world",
0x10,3.1415);
fclose(pfile);
char buff[64]={0};
int data=0;
double d = 0.0;
err=fopen_s(&pfile,file,"r");
if(err!=0)
{
printf("Open file failed\n");
return -1;
}
fscanf_s(pfile,"%s%x%lf",buff,64,&data,&d);
printf("buff:%s,data:%d,d:%lf\n",buff,data,d);
fclose(pfile);
return 0;
}
11.5.3 字符输入输出到文本文件
int char_io()
{
char *path="h:\\doc\\test.dat";
FILE *pfile = NULL;
errno_t err = fopen_s(&pfile,path,"w");
if(err!=0 || pfile==NULL)
{
printf("Open file failed\n");
return -1;
}
char *str="hello world, goodbye world!";
while(*str!='\0')
{
fputc(*str,pfile);
str++;
}
fclose(pfile);
err = fopen_s(&pfile,path,"r");
if(err!=0 ||pfile==NULL)
{
return -1;
}
while(!feof(pfile))
{
printf("%c",fgetc(pfile));
}
printf("\n");
fclose(pfile);
return 0;
}
11.5.4 字符串输入输出到文本文件
int str_io()
{
char *file ="h:\\doc\\str.txt";
FILE
*pfile = NULL;
errno_t err = fopen_s(&pfile,file,"w");
if(err!=0 || pfile==NULL)
{
return -1;
}
fputs("hello world!\n",pfile);//\n-->\r\n
fputs("nice
to meet u\n",pfile);
fclose(pfile);
err = fopen_s(&pfile,file,"r");
if(err!=0 || pfile==NULL)
{
return -1;
}
char buff[1024]={0};
while(!feof(pfile))
{
fgets(buff,1024,pfile);
printf("%s", buff);
memset(buff,0,1024);
}
fclose(pfile);
return 0;
}
在Windows中,文本方式写时,存在”\n””\r\n”的转换,而二进制方式无转换。文本方式读时存在”\r\n”至”\n”的转换,而二进制方式无转换。在linux中文本方式的读写与二进制方式的读写无差别,不存在回车换行间的转换。这样当直接在windows和linux中共享文件时,将会出现与回车换行相关的问题。