关于c语言中文件随机读写的疑惑

来源:互联网  时间:2016/7/14 13:39:43

关于网友提出的“ 关于c语言中文件随机读写的疑惑”问题疑问,本网通过在网上对“ 关于c语言中文件随机读写的疑惑”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: 关于c语言中文件随机读写的疑惑
描述:

oid write_file(char *filename,int *data,char *str,int 
offset)
{
FILE *fp;
int i=0;
if((fp=fopen(filename,"w+"))==NULL)
{
printf("file connot be opened\n");
exit(0);
}
fseek(fp,offset,SEEK_SET);
if(data!=NULL)
{
while(*(data+i)!='\0')
{
fprintf(fp,"%2d",data[i]);
i++;
}
}
i=0;
if(str!=NULL)
{
while(*(str+i)!='\0')
{
fprintf(fp,"%c",str[i]);
i++;
}
}
fclose(fp);
}
为什么我的函数能够实现文件指针的移动,但是在文件指针移动后的位置能存入信息,但是移动后的文件指针前面的信息就消失了,这是怎么回事呀?


解决方案1:

因为你打开文件的时候原始内容都没有了。
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed. 

解决方案2:

你去研究一下"w+"是什么?还有其他的方式也研究一下。

解决方案3:

引用 2 楼  的回复:
因为你打开文件的时候原始内容都没有了。
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"w+"
create text file for update, discard previous contents if any

上一篇位操作运算符
下一篇二叉树遍历中序
明星图片
相关文章
《 关于c语言中文件随机读写的疑惑》由码蚁之家搜集整理于网络,
联系邮箱:mxgf168#qq.com(#改为@)