① 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] = '