在C语言中,fopen一个文件 如何能够在写入新的数据覆盖原文件中指定长度的内容

也就是说假如一个文件中存放了内容 abcdefghijk
现在我要写入IJK到文件中
但是我只想让IJK覆盖原来ijk 而不影响前面的abcdefgh

//给个例子吧:
#include <stdio.h>
void main()
{
char* str1="abcdefghijk";
char* str2="IJK";
FILE *pf=fopen("test.txt","w+");
fwrite(str1, 11, 1, pf);//存储abcdefghijk
fseek(pf, 8, 0);//把文件指针移动到离文件开头8字节处(ijk)
fwrite(str2, 3, 1, pf);//一次写入3个字节的数据到文件
fclose(pf);
}

附加:fseek的第三个参数
SEEK_SET: 文件开头 0

SEEK_CUR: 当前位置 1

SEEK_END: 文件结尾 2追问

好吧!不过以w+打开文件,
写入新的数据会将原来的全部数据覆盖掉
当然根据系统的不同,可能有所区别
经过对所有的读写方式测试:
我发现用r+ 方式打开 可以达到我想要的效果。

追答

那你的fwrite是怎么使用的?你贴下代码。fwrite可以限制写入数据的大小的。例如这里:
fwrite(str2, 3, 1, pf);//一次写入3个字节的数据到文件

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-31

程序示例

  程序示例1  #include  #include //为了使用exit()  int main()  {  char ch;  FILE* fp;  char fname[50]; //用于存放文件名  printf("输入文件名:");  scanf("%s",fname);  fp=fopen(fname,"r"); //只供读取  if(fp==NULL) //如果失败了  {  printf("错误!");  exit(1); //中止程序  }  //getc()用于在打开文件中获取一个字符  while((ch=getc(fp))!=EOF)  putchar(ch);  fclose(fp); //关闭文件  return 0;  }  注意!初学者往往会犯一个错误,即在输入文件名时不加后缀名,请注意加上!  程序示例2[2]  #include  FILE *stream, *stream2;  int main( void )  {  int numclosed;  // Open for read (will fail if file "crt_fopen.c" does not exist)  if( (stream = fopen( "crt_fopen.c", "r" )) == NULL ) // C4996  // Note: fopen is deprecated; consider using fopen_s instead  printf( "The file 'crt_fopen.c' was not opened\n" );  else  printf( "The file 'crt_fopen.c' was opened\n" );  // Open for write  if( (stream2 = fopen( "data2", "w+" )) == NULL ) // C4996  printf( "The file 'data2' was not opened\n" );  else  printf( "The file 'data2' was opened\n" );  // Close stream if it is not NULL  if( stream)  {  if ( fclose( stream ) )  {  printf( "The file 'crt_fopen.c' was not closed\n" );  }  }  // All other files are closed:  numclosed = _fcloseall( );  printf( "Number of files closed by _fcloseall: %u\n", numclosed );  }  [3]


第2个回答  推荐于2018-05-11
先用fopen("xxx", "r+")打开文件,接着用fread把原先数据读到内存

再判断ijk的位置

然后用fseek定位到文件的位置

最后fwrite写文件本回答被网友采纳
第3个回答  2012-08-01
先用fopen("xxx", "r+")打开文件,
接着用fread把原先数据读到内存

再判断ijk的位置

然后用fseek定位到文件的位置

最后fwrite写文件追问

我现在的文件有好几M ,写入buf 实在是……
还不如另外创建一个文件

本回答被网友采纳
第4个回答  2012-09-25
"r"
Opens for reading. If the file does not exist or cannot be found, the fopen call fails.
"w"
Opens an empty file for writing. If the given file exists, its contents are destroyed.
"a"
Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn’t exist.
"r+"
Opens for both reading and writing. (The file must exist.)
"w+"
Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.
"a+"
Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn’t exist.

用a+显然最好 不用判断文件是否存在 写的时候要定位文件位置
相似回答