㈠ C语言中有没有先清除原文件中内容再在该文件中读入新的内容的函数
fopen("文件名","w")就可以了C语言中规定,打开时以"w"方式打开文件时,如果源文件中有内容,先清空源文件的内容再供写入 #include "stdio.h"main(){ FILE *fp; int n; scanf("%d",&n); fp=fopen("temp.txt","w"); fprintf(fp,"%d",n); fclose(fp);}我给你个程序,你运行多次,每次运行时输入不同的值,每次运行完成后查看“temp.txt”文件中的内容,再有问题,和我联系!
㈡ 在C语言中,fopen一个文件 如何能够在写入新的数据覆盖原文件中指定长度的内容
程序示例
程序示例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]#includeFILE *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: fopenis deprecated; consider usingfopen_sinsteadprintf( "The file 'crt_fopen.c' was notopened" );elseprintf( "The file 'crt_fopen.c' wasopened" );// Open for writeif( (stream2 = fopen( "data2", "w+" )) == NULL ) // C4996printf( "The file 'data2' was not opened" );elseprintf( "The file 'data2' was opened" );// Close stream if it is not NULLif( stream){if (fclose( stream ) ){printf( "The file 'crt_fopen.c' was not closed" );}}// All other files are closed:numclosed = _fcloseall( );printf( "Number of files closed by _fcloseall: %u", numclosed );}[3]