① c語言如何實現對txt文件的讀取和寫入
1、使用VS新建空工程,直接點擊確定,如下所示。
② 用c語言怎麼讀取txt文件中的行數
讀取文件行數, 可以逐個字元讀取文件,到文件尾,統計 的個數
參考代碼如下
#include<stdio.h>
intmain()
{
intc;
FILE*fp;
intlines=0;
fp=fopen("in.txt","rb");
if(fp)
{
while((c=fgetc(fp))!=EOF)
if(c==' ')lines++;
printf("%d ",lines);
fclose(fp);
}
return0;
}
也可以通過fgets函數,每次讀取一行,到文件尾,然後計算讀取的次數
#include<stdio.h>
#include<string.h>
intmain()
{
chars[100];
FILE*fp;
intlines=0;
fp=fopen("in.txt","r");
if(fp)
{
while((fgets(s,100,fp))!=NULL)
if(s[strlen(s)-1]==' ')lines++;
printf("%d ",lines);
fclose(fp);
}
return0;
}
③ C語言讀取文件數據並進行計算(平均值,最值,0的個數)
#include
int main()
{ int i,j,n=0,n0=0,k=0;
double a[10000],s=0,t;
FILE *fp;
char c;
if(!(fp=fopen("text.txt","r")))
{printf("File open error!
");
return 0;
}
for(;fscanf(fp,"%lf%c",&a[n],&c)!=-1;n++)
{if(a[n]==0)n0++;
if(c=='
')k++;
s+=a[n];
printf("%g ",a[n]); //不需要顯示時請把此行刪除
}
if(c==32)k++;
fclose(fp);
for(i=0;i<10;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{t=a[j]; a[j]=a[j+1];a[j+1]=t;}
printf("
平均值:%g
",s/n);
printf("前10個最大的數:");
for(i=n-1;i>n-11;i--)
printf("%g ",a[i]);
printf("
0的個數:%d
",n0);
printf("共有%d行
",k);
return 0;
}
④ 如何用C語言讀取TXT格式文件中的數據進行運算
#include<stdio.h>
#include<malloc.h>
voidmain()
{
intn,no,i;
FILE*fp=fopen("data.txt","r);
float*x,*y,result;
if(fp==NULL)return;
fscanf(fp,"%d%d",&n,&no);
x=(float*)malloc(n*sizeof(float);
y=(float*)malloc(n*sizeof(float);
for(i=0;i<n;i++)fscanf("%f%f",x+i,y+i);
result=0.0f;
for(i=0;i<n-1);i++)result+=0.5f*(x[i]*y[i+1]-x[i+1]*y[i]);
printf("%dresultis%f ",no,result);
free(x);
free(y);
fclose(fp);
}
⑤ C語言如何讀取txt文本裡面的內容
C語言可以使用fopen()函數讀取txt文本里。
示例:
#include <stdio.h>
FILE *stream, *stream2;
void main( void )
{
int numclosed;
/* Open for read (will fail if file "data" does not exist) */
if( (stream = fopen( "data", "r" )) == NULL )
printf( "The file 'data' was not opened " );
else
printf( "The file 'data' was opened " );
/* Open for write */
if( (stream2 = fopen( "data2", "w+" )) == NULL )
printf( "The file 'data2' was not opened " );
else
printf( "The file 'data2' was opened " );
/* Close stream */
if(fclose( stream2 ))
printf( "The file 'data2' was not closed " );
/* All other files are closed: */
numclosed = _fcloseall( );
printf( "Number of files closed by _fcloseall: %u ", numclosed );
}
(5)c語言將txt文件讀取計算擴展閱讀
使用fgetc函數
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
FILE *stream;
char buffer[81];
int i, ch;
/* Open file to read line from: */
if( (stream = fopen( "fgetc.c", "r" )) == NULL )
exit( 0 );
/* Read in first 80 characters and place them in "buffer": */
ch = fgetc( stream );
for( i=0; (i < 80 ) && ( feof( stream ) == 0 ); i++ )
{
buffer[i] = (char)ch;
ch = fgetc( stream );
}
/* Add null to end string */
buffer[i] = '