㈠ 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]