㈠ c语言如何实现对txt文件的读取和写入
1、使用VS新建空工程,直接点击确定,如下所示。
㈡ C语言读取文件内容的程序
感觉你贴出来的代码跟题目要求差距有点大啊
代码(ps:这里输入的文件名就是一个相对路径,所以给定的测试文本要放在本程序同目录下):
#include<stdio.h>
#include<stdlib.h>
voidmain()
{
FILE*fp;
charfilename[30],temp[1024];
intcount,i,flag=1;
printf("请输入文件名:");
gets(filename);
if((fp=fopen(filename,"r"))==NULL)//文件不存在
{
printf("FileNameError ");
exit(0);
}
else//文件存在
{
printf("请选择行数:");
scanf("%d",&count);
for(i=1;i<=count;i++)
{
if(fgets(temp,1024,fp)==NULL)//不存在第count行
{
flag=0;
break;
}
}
if(flag==0)
printf("LineNoError ");
else
printf("第%d行是:%s",count,temp);//打印第count行
}
fclose(fp);
}
测试文本内容:
㈢ 用C语言编写读取文件,按照以下要求编写程序
#include<stdio.h>
#define N 10
void main() { FILE *fp; int s1[N]={1,2,13,4,5,61,7,8,9,10},s2[N],i,n;
if ( fp=fopen("D:\file.txt","w+" ) {
for ( i=0;i<N;i++ )fprintf(fp,"%d ",s1[i]);
fclose(fp);
if ( fp=fopen("D:\file.txt","r" ) {
n=0; while ( !feof(fp) ) { fscanf(fp,"%d",&s2[n]); if ( s2[n]%2==0 ) n++; }
fclose(fp);
for ( i=0;i<n;i++ ) printf("%d ",s2[i]); printf(" ");
} else printf("无法打开文件读取数据。
");
}
㈣ 如何用c语言从txt文件中读取数据
//其中的in.txt就是你要读取数据的文件,当然把它和程序放在同一目录
-------------------------------------
#include
<stdio.h>
int
main()
{
int
data;
file
*fp=fopen("in.txt","r");
if(!fp)
{
printf("can't
open
file\n");
return
-1;
}
while(!feof(fp))
{
fscanf(fp,"%d",&data);
printf("%4d",data);
}
printf("\n");
fclose(fp);
return
0;
}
㈤ 怎么用C语言编一个打开txt文件的程序
你可以使用fopen函数,例子如下:
FILE
*fp;/*定义文件类型的指针,它讲指向你所要打开的文件,以后向文件写入数据或者是从文件中读取数据都需要用到他*/
fp=fopen("文件名以及其路径","打开方式");
建议以参考以下几个c函数,你就能够很随意的完成对文件的处理了:
fopen()
字符读写函数:fgetc()和fputc()
字符串读写函数:fgets()和fputs()
格式化读写函数:fcanf()和fprintf()
数据块读写函数:fread()和fwrite()
这些都是对文件操作的基本函数,其中你最好研究一下fopen()函数,那个相对其他的函数要记忆的东西比较多~~
㈥ 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 );
}
(6)用C语言编写程序读取文件扩展阅读
使用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] = '