关于网友提出的“ 关于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.
你去研究一下"w+"是什么?还有其他的方式也研究一下。
解决方案3:"w+"
create text file for update, discard previous contents if any