也就是说假如一个文件中存放了内容 abcdefghijk
现在我要写入IJK到文件中
但是我只想让IJK覆盖原来ijk 而不影响前面的abcdefgh
好吧!不过以w+打开文件,
写入新的数据会将原来的全部数据覆盖掉
当然根据系统的不同,可能有所区别
经过对所有的读写方式测试:
我发现用r+ 方式打开 可以达到我想要的效果。
那你的fwrite是怎么使用的?你贴下代码。fwrite可以限制写入数据的大小的。例如这里:
fwrite(str2, 3, 1, pf);//一次写入3个字节的数据到文件
程序示例
程序示例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]
我现在的文件有好几M ,写入buf 实在是……
还不如另外创建一个文件